如何用mutate across强制列表中tibble的指定列转为字符向量?
问题根源
你代码里的matches("Direct written by (3)")没匹配到目标列,因为括号()是正则表达式的特殊语法(用于分组),没有转义的话,正则引擎会把(3)当作分组规则,而非字面的括号和数字,导致across根本没找到要转换的列,自然列类型没变化。
解决方案
有三种简单的修正方式:
方法1:用fixed()强制字面匹配
给matches()传入fixed()包裹的列名,让它按原始字符串匹配,忽略正则语法:
library(tibble) library(dplyr) library(purrr) data <- list( tibble(A = 1:10, B = 1:10, C = 1:10), tibble(A = 1:10, "Direct written by (3)" = 1:10, C = 1:10), tibble(A = 1:10, B = 1:10, C = 1:10) ) newData <- purrr::map(data, function(dataTable){ mutate(dataTable, across(matches(fixed("Direct written by (3)")), as.character)) })
方法2:直接指定列名(推荐)
既然列名明确,不用正则匹配,直接用反引号包裹特殊列名作为across的选择器:
newData <- purrr::map(data, function(dataTable){ mutate(dataTable, across(`Direct written by (3)`, as.character)) })
方法3:转义正则中的特殊字符
把列名里的括号用双反斜杠转义,让正则引擎识别为字面字符:
newData <- purrr::map(data, function(dataTable){ mutate(dataTable, across(matches("Direct written by \\(3\\)"), as.character)) })
验证结果
执行后查看str(newData),会发现第二个tibble里的Direct written by (3)列类型已经变为chr:
> str(newData[[2]]) tibble [10 × 3] (S3: tbl_df/tbl/data.frame) $ A : int [1:10] 1 2 3 4 5 6 7 8 9 10 $ Direct written by (3): chr [1:10] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" $ C : int [1:10] 1 2 3 4 5 6 7 8 9 10
内容的提问来源于stack exchange,提问作者SJWard
相关产品推荐
相关产品推荐

