为纵向数据框按组添加第一行?

Adding first row by group for longitudinal data frame?

数据框如下所示:

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
..

简单介绍一下我的数据框:超过2k的患者随访年。 我有一列基线 cd4 值,另一列重复测量每位患者的 cd4。现在我想把这两类cd4数据按照subject_ID合并成一列来分析。输出应该是这样的:

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 的解决方案。 提前致谢。

您可以使用 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