[英]When using repeated measures within IDs in R, how do I create a variable for a value from the observation before?
I have data for 3 women with measures repeated across 3 observations (menstrual cycles) each.我有 3 名女性的数据,每个女性在 3 次观察(月经周期)中重复测量。 There is lots of missing data.有很多缺失的数据。
I want to look at the relationship between progesterone this cycle and hb (haemoglobin) last cycle.我想看看这个周期的孕酮和上一个周期的 hb(血红蛋白)之间的关系。
My data currently looks like this:我的数据目前如下所示:
data = data.frame(id = c(1,1,1,2,2,2,3,3,3),
progesterone = c(150, 140, 130, 145, 130, NA, 150, 150, NA),
hb_this_cycle = c(9, 8, 9, NA, 9, 10, 9, 8, 7))
# id progesterone hb
# 1 1 150 9
# 2 1 140 8
# 3 1 130 9
# 4 2 NA NA
# 5 2 130 9
# 6 2 NA 10
# 7 3 150 9
# 8 3 150 8
# 9 3 NA 7
I want to add a variable which represents hb (haemoglobin) from the cycle before.我想添加一个代表之前循环中的 hb(血红蛋白)的变量。 However, I want to do this within IDs.但是,我想在 ID 中执行此操作。 I also need it to be able to handle lots of NAs.我还需要它能够处理大量的 NA。
I would like the data therefore to look like this afterwards ideally:因此,我希望数据在理想情况下看起来像这样:
data_ideal = data.frame(id = c(1,1,1,2,2,2,3,3,3),
progesterone = c(150, 140, 130, 145, 130, NA, 150, 150, NA),
hb_this_cycle = c(9, 8, 9, NA, 9, 10, 9, 8, 7),
hb_last_cycle = c(NA, 9, 8, NA, NA, 9, NA, 9, 8))
# id progesterone hb_this_cycle hb_last_cycle
# 1 1 150 9 NA
# 2 1 140 8 9
# 3 1 130 9 8
# 4 2 145 NA NA
# 5 2 130 9 NA
# 6 2 NA 10 9
# 7 3 150 9 NA
# 8 3 150 8 9
# 9 3 NA 7 8
Any help would be super appreciated.任何帮助将不胜感激。 Thanks.谢谢。
You can do it like below.你可以像下面那样做。 Note that you might have an error in your expected output as the third group receives the last value of the second group which might not be what you want?请注意,您的预期 output 可能有错误,因为第三组收到第二组的最后一个值,这可能不是您想要的?
data_ideal %>% group_by(id) %>% mutate(new = lag(hb_this_cycle))
# A tibble: 9 x 5
# Groups: id [3]
id progesterone hb_this_cycle hb_last_cycle new
<dbl> <dbl> <dbl> <dbl> <dbl>
1 1 150 9 NA NA
2 1 140 8 9 9
3 1 130 9 8 8
4 2 145 NA NA NA
5 2 130 9 NA NA
6 3 NA 10 9 NA
7 3 150 9 NA 10
8 3 150 8 9 9
9 3 NA 7 8 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.