根据值将数据框转换为 2 列数据框

converting a dataframe to a 2 column dataframe based on vaues

我正在尝试将多列数据框转换为 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

哈德利解决方案:

library(dplyr)
library(tidyr)

temp %>% 
   add_rownames() %>% 
   gather(col, val, -rowname) %>% 
   select(-col)

无需额外包的 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

这是我根据请求转换为答案的评论

library(reshape2) 
temp$id <- rownames(temp) 
melt(temp, "id")

或@akrun

的更简单版本
melt(as.matrix(temp))