Вот упрощенная версия, использующая ваши даты (как факторы) для простого извлечения уровня каждой переменной:
data.example = structure(list(pt_id = c(1234L, 1234L, 1234L, 1234L, 4567L, 4567L,
4567L, 4567L, 8900L, 8900L, 8900L, 8900L), assess_date = structure(c(1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("1/1/2019",
"1/2/2019", "1/3/2019", "1/4/2019"), class = "factor"), assess_id = c(64L,
64L, 64L, 64L, 64L, 64L, 64L, 64L, 64L, 64L, 64L, 64L)), class = "data.frame", row.names = c(NA,
-12L))
data.example <- data.example %>%
group_by(pt_id) %>%
mutate(assess_num = as.integer(assess_date))
Если они не являются факторами (пока), то:
data.example <- data.example %>%
group_by(pt_id) %>%
mutate(assess_num = as.integer(as.factor(assess_date)))
Вывод выглядит следующим образом:
# A tibble: 12 x 4
# Groups: pt_id [3]
pt_id assess_date assess_id assess_num
<int> <fct> <int> <int>
1 1234 1/1/2019 64 1
2 1234 1/2/2019 64 2
3 1234 1/3/2019 64 3
4 1234 1/4/2019 64 4
5 4567 1/1/2019 64 1
6 4567 1/2/2019 64 2
7 4567 1/3/2019 64 3
8 4567 1/4/2019 64 4
9 8900 1/1/2019 64 1
10 8900 1/2/2019 64 2
11 8900 1/3/2019 64 3
12 8900 1/4/2019 64 4
РЕДАКТИРОВАТЬ: Вот более явный набор потенциальных решений в зависимости от того, что является исходным классом столбца access_date
:
library(tidyr)
library(dplyr)
# data.example as tibble:
data.example = structure(list(pt_id = c(1234L, 1234L, 1234L, 1234L, 4567L, 4567L,
4567L, 4567L, 8900L, 8900L, 8900L, 8900L), assess_date = structure(c(1L,
2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("1/1/2019",
"1/2/2019", "1/3/2019", "1/4/2019"), class = "factor"), assess_id = c(64L,
64L, 64L, 64L, 64L, 64L, 64L, 64L, 64L, 64L, 64L, 64L)), row.names = c(NA,
-12L), class = c("tbl_df", "tbl", "data.frame"))
# if assess_date is the string class:
data.example <- data.example %>%
group_by(pt_id) %>%
mutate(assess_num = as.integer(as.factor(assess_date)))
# if assess_date is the factor class:
data.example <- data.example %>%
group_by(pt_id) %>%
mutate(assess_num = as.integer(as.factor(as.Date(assess_date,"%m/%d/%Y"))))
# if assess_date is the Date class:
data.example <- data.example %>%
group_by(pt_id) %>%
mutate(assess_num = as.integer(as.factor(assess_date)))