How can I add a data frame to a list in R? I am trying the following code.
First, I create a data frame from a csv file (any csv file will do)
> a <- read.csv(csvFile)
> class(a)
[1] "data.frame"
so, I have a data frame called “a”. Now I create a list with one character item as shown below
> b <- list("hello world")
Now, I append my data frame “a” to the list b as shown below
> b[[length(b)+1]] <- a
> class(b)
[1] "list"
> length(b)
[1] 2
so far so good. List b now has 2 items (the character string “hello world” and the data frame a). Now the piece that puzzles me is the following code
> class(b[2])
[1] "list"
why is class(b[2]) showing up as a list instead of a data frame? I want to be able to add my data frame “a” to the list “b” without having a be converted implicitly into a list. Can anyone help me understand how to do this?
This is documented in
?"["(or?Extract), in the “Recursive (list-like) objects” section (emphasis added):Since
b[2]returns a list, you want to use[[, i.e.b[[2]].