【问题标题】:Adding first row by group for longitudinal data frame?为纵向数据框按组添加第一行?
【发布时间】:2017-02-20 14:18:17
【问题描述】:

这是数据框的样子:

subject_ID  cd4_time0    other_time  cd4_other_time
1           12            0.5            462
1            12            1.0            140 
1            12            3.0           789
1            12           6.0            100
2            4            0.5            230
2            4            1.0            350
2            4            1.9            450
2            4            3.2            550
3         
3
..

简单介绍一下我的数据框:超过 2000 名患者随访多年。 我在基线中有一列 cd4 值,另一列重复测量每位患者的 cd4。现在我想根据subject_ID将这两种cd4数据合并为一列进行分析。输出应该是这样的:

subject_ID  cd4_time0    other_time  cd4_other_time
1            12             0.5            12
1            12             0.5            462
1            12             1.0            140 
1            12            3.0             789
1            12             6.0            100
2            4             0.5             4
2            4             0.5            230
2            4             1.0            350
2            4             1.9            450
2            4             3.2            550
3         
3
..

欢迎任何基于 R 的解决方案。 提前致谢。

【问题讨论】:

  • df1 %>% left_join(df2, by="subject_ID")
  • @c0bra 非常感谢您的回复。但是我认为您没有正确理解我的问题,或者我没有明确表达。第一个 df 是我当前的数据框。我想将第一行添加到另一列,为我的分析制作最终版本的数据框,如上面的第二个 df 所示。不结合这两个df。

标签: r dplyr row longitudinal


【解决方案1】:

您可以使用group_by %>% do 为每个组动态构建数据框的一个选项:

library(dplyr)

df %>% group_by(subject_ID) %>% do ({
# extract and modify the first row
      firstRow <- .[1,]
      firstRow['cd4_other_time'] <- firstRow['cd4_time0']

# bind the first row with the sub data frame . represents a data frame with a unique subject_ID
      bind_rows(firstRow, .)
})

#Source: local data frame [10 x 4]
#Groups: subject_ID [2]

#   subject_ID cd4_time0 other_time cd4_other_time
#        <int>     <int>      <dbl>          <int>
#1           1        12        0.5             12
#2           1        12        0.5            462
#3           1        12        1.0            140
#4           1        12        3.0            789
#5           1        12        6.0            100
#6           2         4        0.5              4
#7           2         4        0.5            230
#8           2         4        1.0            350
#9           2         4        1.9            450
#10          2         4        3.2            550

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2016-12-24
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2014-05-04
    相关资源
    最近更新 更多