在每个列表元素中添加数据框。

3
我正在读取一系列以数据框列表形式结束的文件。在这样做之后,我有兴趣添加与每个数据框相关的额外信息。因此,我想向数据框列表中的每个元素添加一些额外元素。
我的尝试是实际上构建“额外内容”列表,然后尝试将其与数据框列表合并。
示例代码:
set.seed(42)

#Building my list of data.frames. In my specific case this is coming from files
A <- data.frame(x=rnorm(10), y=rnorm(10))
B <- data.frame(x=rnorm(10), y=rnorm(10))

ListD <- list(A, B)
names(ListD)<- c("A", "B") #some names to know what is what

#now my attributes. Each data.frame as some properties that i want to keep track of.
newList <- list(A=c("Color"=123, "Date"=321), B=c("Color"=111, "Date"=111))

#My wished output is a list were each element of the list has 
#"Color", "Date" and a dataframe
#I tried something like:
lapply(ListD, append, values=newList)
3个回答

1
据我所知,您需要做的就是更改ListD的初始化方式:

ListD <- list(list(A), list(B))

因为您需要的数据结构是一个列表,其中内部列表包含一个数据框和两个进一步的属性。我不能保证这正是您想要的结果,但基本上这就是您的问题所在。

1

好的,我以为使用 mapply 会很简单,但是我无法让列表很好地配合在一起...也许其他人可以。所以这里有一个 for 解决方案:

#preallocate list
updatedList <- vector(mode = "list", length = length(ListD)) 
names(updatedList) <- names(ListD)
for(i in 1:length(updatedList)) {
  updatedList[[i]] <- c(ListD[i], newList[[i]])
}
updatedList$A
# $A
# x          y
# 1  -0.51690823  0.4521443
# 2   0.97544933 -0.7212561
# 3   0.98909668 -0.2258737
# 4  -1.72753947 -0.7643175
# 5  -1.31050478 -3.2526437
# 6  -0.63845053  1.1263407
# 7  -0.09010858 -0.9386608
# 8  -0.53933869 -0.6882866
# 9   0.54668290  1.7227261
# 10 -0.87948586 -0.2413344
# 
# $Color
# [1] 123
# 
# $Date
# [1] 321

或者,如果你采用@Яaffael的建议,mapply可以工作,但这将取决于你如何从文件中首先构建列表:

ListD <- list(list(A), list(B))
updatedList <- mapply(c, ListD, newList, SIMPLIFY = FALSE)

0

我采用了@Яaffael的建议,使用了一个列表的列表。

由于我从文件中读取数据的方式使得更改我的数据框列表不是很容易,因此我创建了一个带有额外数据的列表的列表,然后像这样连接数据框:

newList <- list(A=list("Color"=123, "Date"=321), B=list("Color"=111, "Date"=111))

for(n in names(newList)){
  newList[[n]]$Dataframe <- ListD[[n]]
}

我的输出结构:

> str(newList)

List of 2
 $ A:List of 3
  ..$ Color    : num 123
  ..$ Date     : num 321
  ..$ Dataframe:'data.frame':   10 obs. of  2 variables:
  .. ..$ x: num [1:10] 1.371 -0.565 0.363 0.633 0.404 ...
  .. ..$ y: num [1:10] 1.305 2.287 -1.389 -0.279 -0.133 ...
 $ B:List of 3
  ..$ Color    : num 111
  ..$ Date     : num 111
  ..$ Dataframe:'data.frame':   10 obs. of  2 variables:
  .. ..$ x: num [1:10] -0.307 -1.781 -0.172 1.215 1.895 ...
  .. ..$ y: num [1:10] 0.455 0.705 1.035 -0.609 0.505 ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接