当你分配
listz <- list(data.frame("id" = 1:3, "hat" = 1:3),
data.frame("id" = 4:6, "hat" = 4:6))
您正在替换以前定义为 的对象listz
,它是一个新对象,与该名称的任何先前对象无关。
因此在这种情况下不需要初始化列表
你有(至少)四个选项来设置列表的名称
选项1 -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)
选项 2 - 随叫随到
# 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))
选项 3 -Hmisc
和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)
选项 4 - 使用 setNames 预先存在并获取
# if your data.frames already exist in the global environment then
# you can use
listz <- setNames(lapply(listzNames, get),listzNames)
选项 5 初始化列表(我不喜欢这个)
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)
我不喜欢这个选项,它需要更多的输入,因此出错的可能性更大!
注意事项lapply
lapply
将保留任何名称
lapply(listz,head,n=1)
#$frame1
# id hat
#1 1 1
#
#$frame2
# id hat
#1 4 4