我从“开始”开始
ID <- c("A", "A", "A", "B", "B", "C")
Lab <- c("5", "10", "15", "20", "5", "10")
Date <- as.Date(c("01/01/2020",
"01/01/2020",
"01/02/2020",
"01/01/2020",
"01/02/2020",
"01/05/2020"), format="%m/%d/%Y")
Start <- data.frame(ID, Lab, Date)
Start
#> ID Lab Date
#> 1 A 5 2020-01-01
#> 2 A 10 2020-01-01
#> 3 A 15 2020-01-02
#> 4 B 20 2020-01-01
#> 5 B 5 2020-01-02
#> 6 C 10 2020-01-05
,需要进入“完成”。
Day <- c(1, 1, 2, 1, 2, 1)
Finish <- data.frame(ID, Lab, Date, Day)
Finish
#> ID Lab Date Day
#> 1 A 5 2020-01-01 1
#> 2 A 10 2020-01-01 1
#> 3 A 15 2020-01-02 2
#> 4 B 20 2020-01-01 1
#> 5 B 5 2020-01-02 2
#> 6 C 10 2020-01-05 1
每个ID在几天内每天都会有多个实验室。我需要一个新的变量“ Day”,它反映了实验室的绘制日期,每次日期更改时都增加1,并且在患者ID更改时将日期重置为“ 1”。
由reprex package(v0.3.0)于2020-04-16创建
答案 0 :(得分:0)
我们可以在逻辑向量上使用cumsum
来按“ ID”分组后创建“ Day”
library(dplyr)
Start %>%
group_by(ID) %>%
mutate(Day = cumsum(!duplicated(Date)))
# A tibble: 6 x 4
# Groups: ID [3]
# ID Lab Date Day
# <fct> <fct> <date> <int>
#1 A 5 2020-01-01 1
#2 A 10 2020-01-01 1
#3 A 15 2020-01-02 2
#4 B 20 2020-01-01 1
#5 B 5 2020-01-02 2
#6 C 10 2020-01-05 1