使用PURR从数据帧映射字符串 [英] using purr to map strings from dataframes

查看:12
本文介绍了使用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

然后我有另一个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

这篇关于使用PURR从数据帧映射字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆