2012-02-27 106 views
10

我有这样的嵌套数据帧扁平化数据帧

test <- structure(list(id = c(13, 27), seq = structure(list(
`1` = c("1997", "1997", "1997", "2007"), 
`2` = c("2007", "2007", "2007", "2007", "2007", "2007", "2007")), 
.Names = c("1", "2"))), .Names = c("penr", 
"seq"), row.names = c("1", "2"), class = "data.frame") 

我希望所有值的列表中的第二列,即

result <- c("1997", "1997", "1997", "2007", "2007", "2007", "2007", "2007", "2007", "2007", "2007") 

是否有一个简单的方法来实现这一目标?

回答

13

这条线的伎俩:

do.call("c", test[["seq"]]) 

或等效的:

c(test[["seq"]], recursive = TRUE) 

甚至:

unlist(test[["seq"]]) 

这些函数的输出是:

11  12  13  14  21  22  23  24  25  26  27 
"1997" "1997" "1997" "2007" "2007" "2007" "2007" "2007" "2007" "2007" "2007" 

为了摆脱特征向量上面的名字,叫as.character生成的对象:

> as.character((unlist(test[["seq"]]))) 
[1] "1997" "1997" "1997" "2007" "2007" "2007" "2007" "2007" "2007" "2007" 
[11] "2007" 
+0

执行太好了,谢谢! – speendo 2012-02-27 15:21:39

+0

你能在我的答案下面打勾吗?通过这种方式,大家都知道这个问题已经得到解答(我得到了一些代表:)) – 2012-02-27 15:22:56

+0

+ +1显示了三种不错的选择。当然是 – Andrie 2012-02-27 15:24:16

4

这不是一个答案,但跟进/补充保罗的回答是:

始终任何c方法执行最佳的迭代次数。然而,随着我将迭代次数增加到100000次,从最穷的变为非常接近c的方法。

1000次迭代

 test replications elapsed relative user.self sys.self user.child sys.child 
2  c   1000 0.04 1.333333  0.03  0   NA  NA 
1 do.call   1000 0.03 1.000000  0.03  0   NA  NA 
3 unlist   1000 0.23 7.666667  0.04  0   NA  NA 

100000迭代

 test replications elapsed relative user.self sys.self user.child sys.child 
2  c  100000 8.39 1.000000  3.62  0   NA  NA 
1 do.call  100000 10.47 1.247914  4.04  0   NA  NA 
3 unlist  100000 9.97 1.188319  3.81  0   NA  NA 

再次感谢分享保罗!

标杆使用Win 7的机器上rbenchmark运行v 2.14.1

+0

感谢您的基准数据! – 2012-02-27 16:09:42