展平数据框 [英] flatten a data frame

查看:86
本文介绍了展平数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个嵌套的数据框

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")

我想要第二列中所有值的列表,即

I want a list of all values in the second column, namely

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

有没有简单的方法来实现这一目标?

Is there an easy way to achieve this?

推荐答案

以下代码可以解决问题:

This line does the trick:

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:

To get rid of the names above the character vector, call as.character on the resulting object:

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

这篇关于展平数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆