我有一个数据框
name val1 val2
A 2 3
B 5 6
C 7 9
我想要一个数据帧
name Grp value
A val1 2
B val1 5
C val1 7
A val2 3
B val2 6
C val2 9
什么是最佳解决方案?
答案 0 :(得分:3)
它被称为从宽到长格式重塑数据框架。使用包tidyr
:
library(tidyr)
gather(df, Grp, Value, -name)
# name Grp Value
#1 A val1 2
#2 B val1 5
#3 C val1 7
#4 A val2 3
#5 B val2 6
#6 C val2 9
答案 1 :(得分:3)
或者只使用melt
包
reshape2
library(reshape2)
melt(df)
# name variable value
# 1 A val1 2
# 2 B val1 5
# 3 C val1 7
# 4 A val2 3
# 5 B val2 6
# 6 C val2 9
编辑:根据@AnandaMahtos评论,如果您坚持让variable
名称为Grp
,您可以选择:
melt(df, variable.name = "Grp")
答案 2 :(得分:1)
base R
选项是使用stack
cbind(name=df$name, stack(df, select=-name))
# name values ind
#1 A 2 val1
#2 B 5 val1
#3 C 7 val1
#4 A 3 val2
#5 B 6 val2
#6 C 9 val2
答案 3 :(得分:1)
或者没有任何额外的包裹:
ddff<- data.frame(name=c("A","B","C"),val1=c(2,5,7),val2=c(3,6,9))
ddff2<- reshape(ddff,direction="long", varying = list(names(ddff)[2:3]),v.names=c("values"),times=c("val1","val2"))[,1:3]
ddff2
# name time values
#1.val1 A val1 2
#2.val1 B val1 5
#3.val1 C val1 7
#1.val2 A val2 3
#2.val2 B val2 6
#3.val2 C val2 9