简体   繁体   English

从列表的data.frame元素连接一列

[英]Concatenate a column from data.frame elements of a list

I am looking for an idiomatic way to join a column, say named 'x', which exists in every data.frame element of a list. 我正在寻找一种惯用的方式来连接一个名为“ x”的列,该列存在于列表的每个data.frame元素中。 I came up with a solution with two steps by using lapply and Reduce . 我通过使用lapplyReduce提出了一个包含两个步骤的解决方案。 The second attempt trying to use only Reduce failed. 第二次尝试仅使用Reduce尝试失败。 Can I actually use only Reduce with one anonymous function to do this? 我可以只使用带有一个匿名函数的Reduce来执行此操作吗?

#data
xs <- replicate(5, data.frame(x=sample(letters, 10, T), y =runif(10)), simplify = FALSE)
# This works, but may be still unnecessarily long
otmap = lapply(xs, function(df) df$x)
jotm = Reduce(c, otmap)
# This does not count as another solution:
jotm = Reduce(c, lapply(xs, function(df) df$x))

# Try to use only Reduce function. This produces an error
jotr =Reduce(function(a,b){c(a$x,b$x)}, xs)
# Error in a$x : $ operator is invalid for atomic vectors

We can unlist after extracting the 'x' column 我们可以在提取“ x”列后unlist列出

unlist(lapply(xs, `[[`, 'x'))
#[1] b y y i z o q w p d f f z b h m c u f s j e i v y b w j n q e w i r h p z q f x a b v z e x l c q f
#Levels: b d i o p q w y z c f h m s u e j n v r x a l

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM