【问题标题】:How can I transform multiple repeated measures from wide to long format?如何将多个重复测量从宽格式转换为长格式?
【发布时间】:2021-05-12 08:02:48
【问题描述】:

我有一个看起来像这样的数据集:

id          <- c(1:3)
gender      <- factor(c("male","female","female"))
age         <- c(51,69,44)
cortisol_1 <- c(23,32,54)
cortisol_2 <- c(34,52,49)
cortisol_3 <- c(34,65,12)
blood_1    <- c(12,64,54)
blood_2    <- c(52,32,75)
blood_3    <- c(12,12,75)
temp_1     <- c(38.5,38.7,37.9) 
temp_3     <- c(36.5,36.4,37.1)
df          <- data.frame(id,gender,age,cortisol_1,cortisol_2,cortisol_3,blood_1,blood_2,blood_3,temp_1,temp_3)
df

    id gender age cortisol_1 cortisol_2 cortisol_3 blood_1 blood_2 blood_3 temp_1 temp_3
1  1   male  51         23         34         34      12      52      12   38.5   36.5
2  2 female  69         32         52         65      64      32      12   38.7   36.4
3  3 female  44         54         49         12      54      75      75   37.9   37.1

所以我每年在三个时间点测量皮质醇水平和血压。然而,体温仅在基线和第 3 波时进行评估。

如何将数据结构从宽更改为长?我希望数据看起来像这样:

  id gender wave cortisol blood temp
1  1   male    1       23    12 38.5
2  1   male    2       34    52   NA
3  1   male    3       34    12 36.5
4  2 female    1       32    64 37.7
5  2 female    2       52    32   NA
6  2 female    3       65    12 36.4
7  3 female    1       54    54 37.9
8  3 female    2       49    75   NA
9  3 female    3       12    75 37.1

最好的 雅沙

【问题讨论】:

    标签: r pivot transform


    【解决方案1】:

    我们可以使用pivot_longer

    library(dplyr)
    library(tidyr)
    df %>%
      pivot_longer(cols = -c(id, gender, age), 
       names_to = c('.value', 'grp'), names_sep = "_") %>%
      select(-grp)
    

    -输出

    # A tibble: 9 x 6
    #     id gender   age cortisol blood  temp
    #  <int> <fct>  <dbl>    <dbl> <dbl> <dbl>
    #1     1 male      51       23    12  38.5
    #2     1 male      51       34    52  NA  
    #3     1 male      51       34    12  36.5
    #4     2 female    69       32    64  38.7
    #5     2 female    69       52    32  NA  
    #6     2 female    69       65    12  36.4
    #7     3 female    44       54    54  37.9
    #8     3 female    44       49    75  NA  
    #9     3 female    44       12    75  37.1
    

    【讨论】:

    • 非常感谢 Akrun 的快速而有帮助的回复!
    猜你喜欢
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    相关资源
    最近更新 更多