R 是否按组为纵向数据帧添加第一行?
下面是数据框,看起来像:R 是否按组为纵向数据帧添加第一行?,r,dplyr,row,longitudinal,R,Dplyr,Row,Longitudinal,下面是数据框,看起来像: 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
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
..
简要介绍我的数据框架:超过2千名患者随访数年。
我有一列基线中的cd4值,另一列重复测量每个患者的cd4。现在我想根据受试者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的解决方案。
提前谢谢 您可以使用
group\u 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
库(dplyr)
df%%>%分组依据(受试者ID)%%>%do({
#提取并修改第一行
第一行df1%>%left\u join(df2,by=“subject\u ID”)
@c0bra非常感谢您的回复。但我认为您没有正确理解我的问题,或者我没有把它说清楚。第一个df是我当前的数据框。我想将第一行添加到另一列,以生成数据框的最终版本,供我分析,如上面的第二个df所示。不要将这两个df合并。