So I initialize a list, which I want to fill with dataframes:
listz <- vector("list",2)
I also want to keep the dataframes' names around, so I assign them:
listzNames <- c("frame1","frame2")
names(listz) <- listzNames
The problem is, with every reassignment I make to the dataframes, the names go NULL:
listz <- list(data.frame("id" = 1:3, "hat" = 1:3),
data.frame("id" = 4:6, "hat" = 4:6))
> names(listz)
NULL
I know why this happens, but what would be a neat alternative to reassigning the names at every dataframe reassignment?
When you assign
listz <- list(data.frame("id" = 1:3, "hat" = 1:3),
data.frame("id" = 4:6, "hat" = 4:6))
You are replacing the object formerly defined as listz
, it is a new object, unrelated to any previous objects of that name.
Therefore is no need to initialize the list in this case
you have (at least) four options for setting names of a list
setNames
# Option 1 - using setNames
listz <- setNames(list(data.frame("id" = 1:3, "hat" = 1:3),
data.frame("id" = 4:6, "hat" = 4:6)), listzNames)
# Option 2 - naming the list as you go
listz <- list(frame1 = data.frame("id" = 1:3, "hat" = 1:3),
frame2 = data.frame("id" = 4:6, "hat" = 4:6))
Hmisc
and llist
# If your data.frames already exist
# use the llist function in Hmisc, which names the list
# using the names of the object in each element
library(Hmisc)
frame1 <- data.frame("id" = 1:3, "hat" = 1:3)
frame2 <- data.frame("id" = 4:6, "hat" = 4:6)
listz <- llist(frame1,frame2)
# if your data.frames already exist in the global environment then
# you can use
listz <- setNames(lapply(listzNames, get),listzNames)
listz <- vector("list",2)
names(listz) <- listzNames
listz[[1]] <- data.frame("id" = 1:3, "hat" = 1:3)
listz[[2]] <- data.frame("id" = 4:6, "hat" = 4:6)
I don't like this option, it requires more typing and therefore more chance of errors!
lapply
lapply
will preserve any names
lapply(listz,head,n=1)
#$frame1
# id hat
#1 1 1
#
#$frame2
# id hat
#1 4 4
Option 6 :)
listz[] <- list(data.frame("id" = 1:3, "hat" = 1:3),
data.frame("id" = 4:6, "hat" = 4:6))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With