r - 使用 purrr 从数据帧映射字符串

标签 r tidyverse purrr rlang

考虑这个简单的例子

testdf <- data_frame(col1 = c(2, 2),
                     col2 = c(1, 2))

# A tibble: 2 x 2
   col1  col2
  <dbl> <dbl>
1     2     1
2     2     2

然后我有另一个 tibble,其中包含我想要提供给 map2

的参数
mapdf <- data_frame(myinput = c('col1', 'col2'),
                    myoutput = c('col2', 'col1'))

# A tibble: 2 x 2
  myinput myoutput
  <chr>   <chr>   
1 col1    col2    
2 col2    col1 

这是一个简单的函数

myfunc <- function(input, output){
  output <- sym(output)
  input <- sym(input)
    testdf %>% mutate(!!input := !!output + 1)
}

例如,在第一次迭代时,这简单地等于:

> testdf %>% mutate(col1 = col2 + 1)
# A tibble: 2 x 2
   col1  col2
  <dbl> <dbl>
1     2     1
2     3     2

但是,我下面的 purrr 尝试返回一个空数据帧。这里有什么问题吗?

> mapdf %>% map2_dfr(.$myinput, .$myoutput, myfunc(.x, .y))
# A tibble: 0 x 0

谢谢!

最佳答案

您可以使用pmap

pmap(mapdf, ~ myfunc(.x, .y))

[[1]]
# A tibble: 2 x 2
   col1  col2
  <dbl> <dbl>
1     2     1
2     3     2

[[2]]
# A tibble: 2 x 2
   col1  col2
  <dbl> <dbl>
1     2     3
2     2     3

编辑1:按照评论中的建议

pmap_dfr(mapdf, ~ myfunc(.x, .y), .id = 'id')

# A tibble: 4 x 3
  id     col1  col2
  <chr> <dbl> <dbl>
1 1         2     1
2 1         3     2
3 2         2     3
4 2         2     3

编辑2:

还可以使用..1..2..3等引用第#列

pmap_dfr(mapdf, ~ myfunc(input = ..1, output = ..2), .id = 'id')
#> # A tibble: 4 x 3
#>   id     col1  col2
#>   <chr> <dbl> <dbl>
#> 1 1         2     1
#> 2 1         3     2
#> 3 2         2     3
#> 4 2         2     3

要引用列名,我们可以使用 answer 中的技巧。

pmap_dfr(mapdf, ~ with(list(...), myfunc(myinput, myoutput)), .id = 'id')
#> # A tibble: 4 x 3
#>   id     col1  col2
#>   <chr> <dbl> <dbl>
#> 1 1         2     1
#> 2 1         3     2
#> 3 2         2     3
#> 4 2         2     3

关于r - 使用 purrr 从数据帧映射字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52977875/

相关文章:

c++ - 16个嵌套循环速度C++/Rcpp

r - 不推荐在 tibble 上设置行名称。错误 : invalid 'row.names' length

r - 迭代数据帧,其中每次迭代都有效地依赖于 R 中的前一项

r - lm() 在 mutate() 中调用

通过正则表达式替换 quanteda token

r - 管道函数中的消息顺序

r - 如何做条件 NA 填充 R 数据框

r - 使用 dplyr 在 data.frame 中查找逐行最小正非零数

r - 如何在 R 中的任意嵌套列表上替换 NULL 值?

读取多个 xlsx 文件,每个文件都有多个工作表 - purrr