【发布时间】:2016-10-09 19:20:06
【问题描述】:
在下面的示例中,我有一个类似于 xyz 的列表。
> x <- list(a=c("cat", "dog"), b=c("parrot", "chicken"), c=c("animal", "monkey"))
> y <- list(a=c("cat", "dog"), b=c("parrot", "chicken"), c=c("animal", "monkey"))
> z <- list(a=c("cat", "dog"), b=c("parrot", "chicken"), c=c("animal", "monkey"))
> xyz <- list(x, y, z)
> xyz
[[1]]
[[1]]$a
[1] "cat" "dog"
[[1]]$b
[1] "parrot" "chicken"
[[1]]$c
[1] "animal" "monkey"
[[2]]
[[2]]$a
[1] "cat" "dog"
[[2]]$b
[1] "parrot" "chicken"
[[2]]$c
[1] "animal" "monkey"
[[3]]
[[3]]$a
[1] "cat" "dog"
[[3]]$b
[1] "parrot" "chicken"
[[3]]$c
[1] "animal" "monkey"
现在我想为 xyz 中的每个列表提取存储在 $b 中的信息。
xyz 的长度会不时变化,xyz 列表中 b 列的长度也会变化。但我喜欢从中提取信息的总是 b 列。
所需的输出是一个向量,每个列表的 b 列中都有信息。
> desired_output <- data.frame(x=c(xyz[[1]]$b, xyz[[2]]$b, xyz[[3]]$b))
> desired_output
x
1 parrot
2 chicken
3 parrot
4 chicken
5 parrot
6 chicken
我的数据看起来更像。
> x <-list(df=data.frame((c(data.frame(a=c("cat", "dog"), b=c("cat", "dog"))))))
> x <-list(df=data.frame((c(data.frame(a=c("cat", "dog"), b=c("cat", "dog"))))))
> y <-list(df=data.frame((c(data.frame(a=c("cat", "dog"), b=c("cat", "dog"))))))
> z <-list(df=data.frame((c(data.frame(a=c("cat", "dog"), b=c("cat", "dog"))))))
> xyz<- list(x,y,z)
> class(xyz[[1]])
[1] "list"
> class(xyz[[1]]$df)
[1] "data.frame"
> xyz[[1]]$df$b
[1] cat dog
现在我想为 xyz 中的每个数据框提取 b 列中的信息。
【问题讨论】:
-
感谢您的快速评论。我现在看到我的列表结构略有不同。 unlist(lapply(xyz, "[[", "b$c")) 这行不通?
-
你在某处有一个名为 b 且列 c 的 data.frame 吗?
-
是的.. 抱歉重复,这并不能解决我的问题。我有一个列表列表。每个列表都包含一个数据框,我想提取数据框“b”列中的所有信息。如果我找不到答案,我会写一个更好的问题。感谢您的帮助。
-
到目前为止发布的所有解决方案都适用于您提供的示例数据。如果你需要为一个新问题提出一个新问题,那就是一个新问题。首先对 SO 进行可靠搜索,因为其他人之前可能遇到过同样的问题。
标签: r