我正在尝试将多列数据帧转换为2列数据帧。每行都是具有多个属性的人(基于第一列中的id)。如何在2列中列出每个人和属性?
示例:
temp<-data.frame(V1 = c(1,2,3),V2 = c(4,5,6))
row.names(temp)<-c("person1","person2","person3")
temp
V1 V2
person1 1 4
person2 2 5
person3 3 6
res<-data.frame(person=c("person1","person1","person2","person2","person3",
"person3"),val= c(1,4,2,5,3,6))
res
person val
1 person1 1
2 person1 4
3 person2 2
4 person2 5
5 person3 3
6 person3 6
答案 0 :(得分:1)
哈德利溶液:
library(dplyr)
library(tidyr)
temp %>%
add_rownames() %>%
gather(col, val, -rowname) %>%
select(-col)
答案 1 :(得分:1)
这是我的评论转换为每个请求的答案
library(reshape2)
temp$id <- rownames(temp)
melt(temp, "id")
或者@akrun的简单版本
melt(as.matrix(temp))
答案 2 :(得分:0)
Base R解决方案,无需额外包装:
> temp$person <- row.names(temp)
> row.names(temp) <- NULL
> temp
V1 V2 person
1 1 4 person1
2 2 5 person2
3 3 6 person3
> reshape(data = temp,
+ varying = list(c("V1","V2")),
+ v.names = "val",
+ idvar = "person",
+ direction = "long")
person time val
person1.1 person1 1 1
person2.1 person2 1 2
person3.1 person3 1 3
person1.2 person1 2 4
person2.2 person2 2 5
person3.2 person3 2 6