如何在mutate中结合across使用str_replace_all批量处理tibble列
问题原因
你写的代码未生效是因为across()调用函数时,没有正确将遍历到的列值传入str_replace_all()的第一个参数。str_replace_all()要求第一个参数为待处理的字符向量,你直接写str_replace_all("-", "")相当于把-当成了待处理的向量,自然无法得到预期结果。
正确实现(无需加载purrr包)
仅用dplyr自带的across()即可完成需求,不需要额外依赖purrr,有两种常用写法:
写法1:使用公式语法(可读性更高)
用.x代指当前遍历到的每一列:
library(dplyr) library(stringr) starwars %>% mutate( across(everything(), ~str_replace_all(.x, pattern = "-", replacement = "")) )
写法2:直接传函数参数
将str_replace_all除第一个参数外的其他参数直接写在across()的后续位置即可:
starwars %>% mutate( across(everything(), str_replace_all, pattern = "-", replacement = "") )
优化建议
如果你的tibble包含非字符类型的列(比如数值、逻辑值、列表列等),直接对所有列调用str_replace_all会报错,建议只对字符列执行替换操作:
starwars %>% mutate( across(where(is.character), ~str_replace_all(.x, "-", "")) )
内容的提问来源于stack exchange,提问作者Dario Lacan
相关产品推荐
相关产品推荐

