1

这是看起来像的数据框:

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

4

1 回答 1

2

您可以使用一个选项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
于 2017-02-20T14:27:49.593 回答