我有一个数据文件,其中各个样本由空行分隔,每个字段都在自己的行上:
age 20
weight 185
height 72
age 87
weight 109
height 60
age 15
weight 109
height 58
...
如何将此文件读入数据帧,使每一行代表一个包含年龄、体重、身高列的样本?
age weight height
1 20 185 72
2 87 109 60
3 15 109 58
...
@user1317221_G 展示了我将采取的方法,但诉诸于加载额外的包并显式生成组。组(ID 变量)是获取任何内容的关键reshape
输入工作答案。矩阵答案没有这个限制。
这是 R 基础中密切相关的方法:
mydf <- read.table(header = FALSE, stringsAsFactors=FALSE,
text = "age 20
weight 185
height 72
age 87
weight 109
height 60
age 15
weight 109
height 58
")
# Create your id variable
mydf <- within(mydf, {
id <- ave(V1, V1, FUN = seq_along)
})
使用 id 变量,您的转换很容易:
reshape(mydf, direction = "wide",
idvar = "id", timevar="V1")
# id V2.age V2.weight V2.height
# 1 1 20 185 72
# 4 2 87 109 60
# 7 3 15 109 58
Or:
# Your ids become the "rownames" with this approach
as.data.frame.matrix(xtabs(V2 ~ id + V1, mydf))
# age height weight
# 1 20 72 185
# 2 87 60 109
# 3 15 58 109
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)