[英]Add column in r with the preview values in another column
I have a data frame with 2 columns.我有一个包含 2 列的数据框。 Patient_Id and time (when visit the doctor). Patient_Id 和时间(看医生时)。 I would like to add a new column "timestart" which have 0 at the first row for each different Patient_id and the other rows with the same id have the preview value from column time.我想添加一个新列“timestart”,其中每个不同的 Patient_id 在第一行都有 0,而其他具有相同 id 的行具有列时间的预览值。 I think to do this with loop for, but I am new user in R and I don't know how.我想用循环来做到这一点,但我是 R 的新用户,我不知道如何。 Thanks in advance.提前致谢。
We can group by 'Patient_id' and create the new column with the lag
of 'time'我们可以按“Patient_id”分组并创建具有“时间” lag
的新列
library(dplyr)
df1 %>%
group_by(Patient_id) %>%
mutate(timestart = lag(time, default = 0))
# Patient_id time timestart
# <int> <int> <int>
#1 1 1 0
#2 1 2 1
#3 1 3 2
#4 2 1 0
#5 2 2 1
#6 2 3 2
df1 <- data.frame(Patient_id = rep(1:2, each = 3), time = 1:3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.