[英]R: {reshape}: (melt.data.frame) How do I replicate a column?
[英]How can I melt a matrix data frame in R with 2 variables and 1 value column?
我的数据如下所示:
col1 col2 col3
col1 100 25 30
col2 25 200 50
col3 30 50 300
其中列名和行名是 c("col1", "col2", "col3")
我希望它看起来像这样:
Var1 Var2 Value
col1 col1 100
col1 col2 25
col1 col3 30
col2 col1 25
col2 col2 200
col2 col3 50
col3 col1 30
col3 col2 50
col3 col3 300
我正在尝试 reshape2::melt 但它没有给我我正在寻找的结果melt(df)
,任何帮助表示赞赏!
谢谢你。
在为table
创建属性后,我们可以将base R
与as.data.frame
一起使用
as.data.frame.table(m1)
# Var1 Var2 Freq
#1 col1 col1 100
#2 col2 col1 25
#3 col3 col1 30
#4 col1 col2 25
#5 col2 col2 200
#6 col3 col2 50
#7 col1 col3 30
#8 col2 col3 50
#9 col3 col3 300
m1 <- structure(c(100L, 25L, 30L, 25L, 200L, 50L, 30L, 50L, 300L),
.Dim = c(3L,
3L), .Dimnames = list(c("col1", "col2", "col3"), c("col1", "col2",
"col3")))
tidyr 包正是您所需要的
library(tidyr)
df <- gather(df, 'Var2', 'Value' 2:4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.