将多个列合并为一个(R)[重复]

时间:2021-12-14 09:26:58

This question already has an answer here:

这个问题已经有了答案:

I have a question regarding the combination of multiple columns into one column. There is probably a not so fancy solution, but I don't get it the way I want.

我有一个问题关于把多列合并成一列。可能有一个不那么花哨的解决方案,但我没有按照我想要的方式去做。

The dataset I have looks like this:

我的数据集是这样的:

ID  TIME  M1   M2   M3
1   1     0.5  1.5  2
1   2     0.7  1.8  3
2   1     0.3  1.4  1.5
2   2     0.6  1.5  2.3

What I want to do is somehow combine the columns M1 to M3 in this way:

我想要做的是把M1和M3结合起来:

ID  TIME  Mall  Value  
1   1     M1    0.5
1   1     M2    1.5
1   1     M3    2
1   2     M1    0.7
1   2     M2    1.8
1   2     M3    3

etc.

等。

Thanks in advance!

提前谢谢!

2 个解决方案

#1


2  

This is a classic reshape problem. Consider using the reshape2 package

这是一个典型的重塑问题。考虑使用reshape2包。

library(reshape2)
melt(dd, id.vars=c("ID","TIME"), variable.name="Mall")

#2


0  

Using base reshape:

使用基础重塑:

> reshape(dat, varying=c('M1','M2','M3'), v.names='Mall', timevar='TIME', direction='long')
    ID TIME Mall id
1.1  1    1  0.5  1
2.1  1    1  0.7  2
3.1  2    1  0.3  3
4.1  2    1  0.6  4
1.2  1    2  1.5  1
2.2  1    2  1.8  2
3.2  2    2  1.4  3
4.2  2    2  1.5  4
1.3  1    3  2.0  1
2.3  1    3  3.0  2
3.3  2    3  1.5  3
4.3  2    3  2.3  4

#1


2  

This is a classic reshape problem. Consider using the reshape2 package

这是一个典型的重塑问题。考虑使用reshape2包。

library(reshape2)
melt(dd, id.vars=c("ID","TIME"), variable.name="Mall")

#2


0  

Using base reshape:

使用基础重塑:

> reshape(dat, varying=c('M1','M2','M3'), v.names='Mall', timevar='TIME', direction='long')
    ID TIME Mall id
1.1  1    1  0.5  1
2.1  1    1  0.7  2
3.1  2    1  0.3  3
4.1  2    1  0.6  4
1.2  1    2  1.5  1
2.2  1    2  1.8  2
3.2  2    2  1.4  3
4.2  2    2  1.5  4
1.3  1    3  2.0  1
2.3  1    3  3.0  2
3.3  2    3  1.5  3
4.3  2    3  2.3  4