r - 使用 pmap 将不同的正则表达式应用于 tibble 中的不同变量?
问题描述
我正在尝试将不同的正则表达式应用于小标题中的不同变量。例如,我制作了一个 tibble 列表 1) 我要修改的变量名,2) 我要匹配的正则表达式,以及 3) 替换字符串。我想将正则表达式/替换应用于不同数据框中的变量。
所以我的“配置”标题看起来像这样:
test_config <- dplyr::tibble(
string_col = c("col1", "col2", "col3", "col4"),
pattern = c("^\\.$", "^NA$", "^NULL$", "^$"),
replacement = c("","","", "")
)
我想将此应用于目标小标题:
test_target <- dplyr::tibble(
col1 = c("Foo", "bar", ".", "NA", "NULL"),
col2 = c("Foo", "bar", ".", "NA", "NULL"),
col3 = c("Foo", "bar", ".", "NA", "NULL"),
col4 = c("NULL", "NA", "Foo", ".", "bar")
)
因此,目标是在 test_target 的每一列/变量中用空字符串替换不同的字符串。
结果应该是这样的:
result <- dplyr::tibble(
col1 = c("Foo", "bar", "", "NA", "NULL"),
col2 = c("Foo", "bar", ".", "", "NULL"),
col3 = c("Foo", "bar", ".", "NA", ""),
col4 = c("NULL", "NA", "Foo", ".", "bar")
)
我可以用 for 循环做我想做的事,如下所示:
for (i in seq(nrow(test_config))) {
test_target <- dplyr::mutate_at(test_target,
.vars = dplyr::vars(
tidyselect::matches(test_config$string_col[[i]])),
.funs = dplyr::funs(
stringr::str_replace_all(
., test_config$pattern[[i]],
test_config$replacement[[i]]))
)
}
相反,有没有更整洁的方式来做我想做的事?到目前为止,我认为这purrr::pmap
是完成这项工作的工具,我制作了一个函数,它接受数据框、变量名称、正则表达式和替换值,并返回修改了单个变量的数据框。它的行为符合预期:
testFun <- function(df, colName, regex, repVal){
colName <- dplyr::enquo(colName)
df <- dplyr::mutate_at(df,
.vars = dplyr::vars(
tidyselect::matches(!!colName)),
.funs = dplyr::funs(
stringr::str_replace_all(., regex, repVal))
)
}
# try with example
out <- testFun(test_target,
test_config$string_col[[1]],
test_config$pattern[[1]],
"")
但是,当我尝试将该函数与 pmap 一起使用时,我遇到了几个问题:1) 有没有比这更好的方法来构建 pmap 调用的列表?
purrr::pmap(
list(test_target,
test_config$string_col,
test_config$pattern,
test_config$replacement),
testFun
)
2) 当我调用 pmap 时,我得到一个错误:
Error in UseMethod("tbl_vars") :
no applicable method for 'tbl_vars' applied to an object of class "character"
Called from: tbl_vars(tbl)
你们中的任何人都可以提出一种使用 pmap 来做我想做的事情的方法,或者是否有不同或更好的 tidyverse 方法来解决这个问题?
谢谢!
解决方案
另一种使用方法map2_dfc
(_dfc
后缀也可用于pmap
):
library(dplyr)
library(purrr)
map2_dfc(test_target, seq_along(test_target),
~sub(test_config$pattern[.y],
test_config$replacement[.y], .x))
或imap_dfc
(请注意,这样会丢失列名):
imap_dfc(unname(test_target),
~sub(test_config$pattern[.y],
test_config$replacement[.y], .x))
输出:
# A tibble: 5 x 4
col1 col2 col3 col4
<chr> <chr> <chr> <chr>
1 Foo Foo Foo NULL
2 bar bar bar NA
3 "" . . Foo
4 NA "" NA .
5 NULL NULL "" bar
推荐阅读
- amazon-web-services - 添加 2 个父路径时,AWS Api 网关 {proxy+} 引发内部服务器错误
- arrays - 为什么打印错误的数字 1?
- kotlin - 可以在 kotlin 中用字符串获取颜色吗?
- python - 带有任意大小障碍物的矩阵右下角的方式数向右或向下跳跃
- android - 在 ViewPager 中的片段之间传递数据,但触发器位于 MainActivity
- python - Python函数在排序列表中查找第一个非负数?
- c++ - std::multimap 上的 emplace_hint 是否保留等效元素的相对顺序?
- python - Python subprocess.call() 异常后保持子进程窗口打开
- r - 关于 purrr::walk 的困惑
- php - 获取Ajax打开模态,进行PHP函数调用并将结果放入模态