考虑这个简单的例子
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/