r语言 - 在 dplyr 突变(交叉)调用中创建因子失败



在具有 NA 的数据集中创建因子水平适用于单个列,但我需要遍历更多列(所有列都以"影响"开头(,并且在 dplyr 突变(跨(中遇到了问题

我做错了什么?

下面的参考

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的快捷方式 - 有关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

最新更新