这个问题在这里已经有了答案:
Reshaping multiple sets of measurement columns (wide format) into single columns (long format)
(7 个回答)
去年关闭。
我对 R 比较陌生,并且有如下宽格式的数据
subject_id age sex treat1.1.param1 treat1.1.param2 treat1.2.param1 treat1.2.param2
-----------------------------------------------------------------------------------------------
1 23 M 1 2 3 4
2 25 W 5 6 7 8
这是我们针对给定治疗(此处为treat1)在多轮重复测量(此处为第1轮和第2轮)中测量多个参数(此处为param1和param2)的几个主题的数据。该主题的条目所属的处理、舍入和参数的信息在列标题中编码,如上例所示。
我想将长格式的数据举例如下:
subject_id age sex treatment round param1 param2
------------------------------------------------------------------------------------------
1 23 M treat1 1 1 2
1 23 M treat1 2 3 4
2 25 W treat1 1 5 6
2 25 W treat1 2 7 8
也就是说,标识单个观察的 id 变量是 subject_id、treatment、round。但是由于后两个变量使用点作为分隔符在列标题中进行编码,因此我不知道如何从宽格式转换为长格式。所有使用标准示例(使用
reshape2
或 tidyr
)的尝试都失败了。因为实际上,我每 30 轮有 12 次治疗,每轮大约有 50 个参数,因此相对手动的方法对我没有太大帮助。
最佳答案
我们可以使用 pivot_longer
来自 tidyr
指定 names_to
和 names_pattern
争论。
tidyr::pivot_longer(df,
cols = starts_with("treat"),
names_to = c("treatmeant", "round", ".value"),
names_pattern = "(\\w+)\\.(\\d+)\\.(\\w+)")
# subject_id age sex treatmeant round param1 param2
# <int> <int> <fct> <chr> <chr> <int> <int>
#1 1 23 M treat1 1 1 2
#2 1 23 M treat1 2 3 4
#3 2 25 W treat1 1 5 6
#4 2 25 W treat1 2 7 8
数据
df <- structure(list(subject_id = 1:2, age = c(23L, 25L), sex = structure(1:2,
.Label = c("M", "W"), class = "factor"),
treat1.1.param1 = c(1L, 5L), treat1.1.param2 = c(2L, 6L),
treat1.2.param1 = c(3L, 7L), treat1.2.param2 = c(4L, 8L)),
class = "data.frame", row.names = c(NA, -2L))
关于r - 在列标题中编码 id 变量时将数据从宽格式转换为长格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59891956/