在 dplyr mutate(across) 调用中创建因子失败

Creating factors fails inside dplyr mutate(across) call

在具有 NA 的数据集中创建因子水平适用于各个列,但我需要遍历更多列(所有列都以 'impact.' 开头)并且在 dplyr mutate(across)

我做错了什么?

下面的 Reprex

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)))

只是将@27ϕ9 的评论作为答案:您在 across 中指定的 purrr 风格的 lambda 函数不正确,因为它需要第一个参数,这是函数应该引用的对象(在这种情况下,across 选择的数据框列)。

要解决您的问题,您应该在 lambda 函数中插入 .x,它是 function(x) x 的快捷方式 - 请参阅此 page 了解有关 purrr 风格的 lambda 函数。

df %>% 
  mutate(across(.cols = starts_with('impact'), ~factor(.x, levels = 1:5, labels = trt_labels)))

# A tibble: 5 x 4
#      id tumour impact.chemo impact.radio
#   <dbl> <chr>  <fct>        <fct>       
# 1     1 lung   NA           Planned     
# 2     2 lung   Planned      NA          
# 3     3 lung   Modified     Interrupted 
# 4     4 meso   Interrupted  Deferred    
# 5     5 lung   Deferred     Omitted