首页 > 解决方案 > 使用 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 方法来解决这个问题?

谢谢!

标签: rpurrr

解决方案


另一种使用方法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 

推荐阅读