统一两列并创建一列以指示先前的统一列名称

时间:2019-04-07 08:41:03

标签: r

我想将两列中的值统一起来,并创建另一列,该列从头开始指示两列的列名。

structure(list(moda = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L), .Label = c("BS1", "HW1", "PG"), class = "factor"), 
t0 = c(1.5, 1.5, 2, 1, 1.5, 1.2, 1, 2.4, 1.3, 1.4, 1.7, 2, 
1.8, 2.3, 2.5, 2.5, 1.5, 1.5, 2, 2.1, 1.8, 1.3, 2, 1.5, 2, 
3.5, 1.5, 1.7), t14 = c(1.5, 1.5, 2, 1, 1.5, 1.2, 1, 2.4, 
1.3, 1.4, 5, 7, 2.5, 6.5, 5.4, 5, 6, 5.7, 7, 3.5, 4.7, 4.5, 
5.9, 5, 6, 7, 6, 5.5)), class = "data.frame", row.names = c(NA, 
-28L))
structure(list(moda = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "HW1",       class = "factor"), 
time = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("t0", 
"t14"), class = "factor"), unified = c(1.7, 2, 1.8, 5, 7, 
2.5)), class = "data.frame", row.names = c(NA, -6L))

因此,想法是将t0和t14列的末尾统一为一个新列。并获得另一个列,该列为统一列的每个值指示t0或t14。 编辑第二个结构,说明所需输出的简短示例。

1 个答案:

答案 0 :(得分:3)

我们可以在此处使用gather

library(tidyr)
dflong <-  gather(df1, time, unified, t0:t14)