所以我初始化一个列表,我想填充数据帧:
listz <- vector("list",2)
我还想保留数据帧的名称,所以我分配它们:
listzNames <- c("frame1","frame2")
names(listz) <- listzNames
问题是,每次对数据帧进行重新分配,名称都为NULL:
listz <- list(data.frame("id" = 1:3, "hat" = 1:3),
data.frame("id" = 4:6, "hat" = 4:6))
> names(listz)
NULL
我知道为什么会发生这种情况,但在每次数据帧重新分配时重新分配名称会有什么好处?
答案 0 :(得分:10)
分配时
listz <- list(data.frame("id" = 1:3, "hat" = 1:3),
data.frame("id" = 4:6, "hat" = 4:6))
您正在替换以前定义为listz
的对象,它是一个新对象,与该名称的任何先前对象无关。
因此在这种情况下无需初始化列表
您(至少)有四个用于设置列表名称的选项
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
和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)
我不喜欢这个选项,它需要更多的输入,因此更有可能出错!
lapply
lapply
将保留所有名称
lapply(listz,head,n=1)
#$frame1
# id hat
#1 1 1
#
#$frame2
# id hat
#1 4 4
答案 1 :(得分:2)
选项6:)
listz[] <- list(data.frame("id" = 1:3, "hat" = 1:3),
data.frame("id" = 4:6, "hat" = 4:6))