Длина - это проблема, мы можем либо вставить ее вместе, либо создать столбец списка
library(dplyr)
conditions %>%
group_by(session)%>%
mutate(unique_codes = toString(unique(codes)))
Или другой вариант - установить значение length
, добавив NA
в конце
conditions %>%
group_by(session) %>%
mutate(unique_codes = `length<-`(unique(codes), n()))
# A tibble: 14 x 4
# Groups: session [4]
# session condition codes unique_codes
# <int> <chr> <int> <int>
# 1 15 anxiety 1 1
# 2 15 depression 1 3
# 3 15 bipolar 1 NA
# 4 15 high blood pressure 3 NA
# 5 15 panic attacks 1 NA
# 6 66 hypertension 5 5
# 7 66 high blood pressure 3 3
# 8 66 anxiety 1 1
# 9 66 panic attacks 1 NA
#10 75 schizophrenia 1 1
#11 32 muscular dystrophy 4 4
#12 32 anxiety 1 1
#13 32 depression 1 NA
#14 32 panic attacks 1 NA
В OP упоминается, что n()
не работает (может быть проблема с dplyr
версией). В этом случае length
должно работать
conditions %>%
group_by(session) %>%
mutate(unique_codes = `length<-`(unique(codes), length(codes)))
data
conditions <- structure(list(session = c(15L, 15L, 15L, 15L, 15L, 66L, 66L,
66L, 66L, 75L, 32L, 32L, 32L, 32L), condition = c("anxiety",
"depression", "bipolar", "high blood pressure", "panic attacks",
"hypertension", "high blood pressure", "anxiety", "panic attacks",
"schizophrenia", "muscular dystrophy", "anxiety", "depression",
"panic attacks"), codes = c(1L, 1L, 1L, 3L, 1L, 5L, 3L, 1L, 1L,
1L, 4L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA,
-14L))