在具有 NA 的数据集中创建因子级别适用于单个列,但我需要遍历更多列(均以“影响”开头)并且在 dplyr mutate(across) 中遇到了问题
我究竟做错了什么?
下面的代表
library(tribble)
library(dplyr)
df <- tribble(~id, ~tumour, ~impact.chemo, ~impact.radio,
1,'lung',NA,1,
2,'lung',1,NA,
3,'lung',2,3,
4,'meso',3,4,
5,'lung',4,5)
# Factor labels
trt_labels <- c('Planned', 'Modified', 'Interrupted', 'Deferred', "Omitted")
# Such that factor levels match labels as, retaining NAs where present:
data.frame(level = 1:5,
label = trt_labels)
# Create factor works for individual columns
factor(df$impact.chemo, levels = 1:5, labels = trt_labels)
factor(df$impact.radio, levels = 1:5, labels = trt_labels)
# But fails inside mutate(across)
df %>%
mutate(across(.cols = starts_with('impact'), ~factor(levels = 1:5, labels = trt_labels)))