[英]Select date from a previous observation and input it into a new column in R
I am working on patient health records and trying to find the last clinic visit from there first clinic visit, Below is the data frame :- 我正在处理患者的健康记录,并尝试从那里的第一次门诊中查找最后一次门诊,以下是数据框:-
patient_id admit_date
P1 05/1/2015
P2 09/10/2015
P1 08/5/2015
P1 09/10/2015
P2 12/1/2015
The output should be :- 输出应为:-
patient_id admit_date last_visit
P1 05/1/2015 NA
P2 09/10/2015 NA
P1 08/5/2015 05/1/2015
P1 09/10/2015 08/5/2015
P2 12/1/2015 09/10/2015
I was planning on using the dplyr approach :- 我正计划使用dplyr方法:-
raw_data %>%
group_by(patient_id) %>% mutate(last_visit= )
I need some guidance in the mutate part. 在变异部分,我需要一些指导。
First, convert the date format to a proper date, then use lag
to go one time period back: 首先,将日期格式转换为适当的日期,然后使用
lag
返回一个时间段:
library(dplyr)
rawdata %>% group_by(patient_id) %>%
mutate(admit_date = as.Date(admit_date, format = "%d/%m/%Y"),
last_visit = lag(admit_date))
Source: local data frame [5 x 3]
Groups: patient_id [2]
patient_id admit_date last_visit
(fctr) (date) (date)
1 P1 2015-01-05 <NA>
2 P2 2015-10-09 <NA>
3 P1 2015-05-08 2015-01-05
4 P1 2015-10-09 2015-05-08
5 P2 2015-01-12 2015-10-09
Your dates are ambiguous - if you have dmy this is correct, otherwise change the format argument to "%m/%d/%y"
您的日期不明确-如果您有dmy,这是正确的,否则将format参数更改为
"%m/%d/%y"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.