简体   繁体   中英

Add column in r with the preview values in another column

I have a data frame with 2 columns. Patient_Id and time (when visit the doctor). 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. I think to do this with loop for, but I am new user in R and I don't know how. Thanks in advance.

We can group by 'Patient_id' and create the new column with the lag of 'time'

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

data

df1 <- data.frame(Patient_id = rep(1:2, each = 3), time = 1:3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM