首页 > 解决方案 > 使用 purr 映射数据帧中的字符串

问题描述

考虑这个简单的例子

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

然后我有另一个小标题,其中包含我想要提供的参数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

谢谢!

标签: rtidyversepurrrrlang

解决方案


您可以使用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

要改为引用列名,我们可以使用this 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

推荐阅读