r - 在列标题中编码 id 变量时将数据从宽格式转换为长格式

标签 r tidyr reshape2

这个问题在这里已经有了答案:





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。但是由于后两个变量使用点作为分隔符在列标题中进行编码,因此我不知道如何从宽格式转换为长格式。所有使用标准示例(使用 reshape2tidyr )的尝试都失败了。因为实际上,我每 30 轮有 12 次治疗,每轮大约有 50 个参数,因此相对手动的方法对我没有太大帮助。

最佳答案

我们可以使用 pivot_longer来自 tidyr指定 names_tonames_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/

相关文章:

r - 使用 tidyverse 清理排名选择调查

R:将解释变量的动态数量拟合到多项式回归中

r - "Multi-step"在 R 中使用 broom 和 dplyr 进行回归

r - 熔化多行

r - 如何将具有熔化或聚集功能的 2 列中的 6 个特定列堆叠?

r - 是否有任何变通方法可以从 Rstudio 中获取插入符包工作的 train() 函数?

r - 创建新变量,它是许多其他变量的线性组合

按正则表达式/模式对多列重新排序和分组

r - 在 unnest_wider 之后命名提升向量中的列

重新构建置信区间的输出,将平均值、上限和下限合并到一个单元格中