Create a list
Just like a grocery list, lists in R can be used to hold together items of different data types. Creating a list is, you guessed it, as simple as using the list()
function. You could say that a list is a kind of super data type: you can store practically any piece of information in it! Create a list like so:
words <- c("I <3 R")
numbers <- c(42, 24)
my_list <- list(words, numbers)
my_list
[[1]]
[1] "I <3 R"
[[2]]
[1] 42 24
Below, you will create your first list from some of the data you have already worked with!
This exercise is part of the course
Introduction to R for Finance
Exercise instructions
- The 4 components for your list have been created for you.
- Use
list()
to create a list ofname
,apple
,ibm
, andcor_matrix
, in that order, and assign it toportfolio
. - Print your
portfolio
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# List components
name <- "Apple and IBM"
apple <- c(109.49, 109.90, 109.11, 109.95, 111.03)
ibm <- c(159.82, 160.02, 159.84, 160.35, 164.79)
cor_matrix <- cor(cbind(apple, ibm))
# Create a list
portfolio <-
# View your first list