Adding to a list
Once you create a list, you aren't stuck with it forever. You can add new elements to it whenever you want! Say you want to add your friend Dan's favorite movie to your list. You can do so using $
like you did when adding new columns to data frames.
my_list$dans_movie <- "StaR Wars"
my_list
$my_words
[1] "I <3 R"
$my_numbers
[1] 42 24
$dans_movie
[1] "StaR Wars"
You could have also used c()
to add another element to the list: c(my_list, dans_movie = "StaR Wars")
. This can be useful if you want to add multiple elements to your list at once.
This exercise is part of the course
Introduction to R for Finance
Exercise instructions
- Another useful piece of information for your
portfolio
is the variableweight
describing how invested you are in Apple and IBM. Fill in the___
correctly so that you are invested 20% in Apple and 80% in IBM. Remember to use decimal numbers, not percentages! - Print
portfolio
to see theweight
element. - You can change the data in a list in the same way as adding to it using
$
. Createweight
to be invested 30% in Apple and 70% in IBM. - Print
portfolio
again to see your changes.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Add weight: 20% Apple, 80% IBM
portfolio$___ <- c(apple = ___, ibm = ___)
# Print portfolio
# Change the weight variable: 30% Apple, 70% IBM
portfolio$___ <- c(apple = ___, ibm = ___)
# Print portfolio to see the changes