r - 使用 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
谢谢!
解决方案
您可以使用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
推荐阅读
- c# - 如何从 Angular .Netcore 应用程序发送带有附件的电子邮件?
- shell - 为什么我在 cmd 中的 1 行命令不起作用?
- php - 如何确保图像和文本是响应式的?
- video - 当在两个不同帧率的视频中截屏时,我需要使用可变帧率吗
- ios - 如何让我选择的图像按照它们被选择的顺序出现?
- jquery - 通过 jQuery 实现 Foursquare API 来查找餐厅
- c# - 实体框架 MVC 代码优先 BIND 不适用于 EDIT 操作中的子实体
- twitter-bootstrap - 带有 bootstrap-vue 输入框的 Mapbox Geocoder - mapbox 的自定义搜索框
- sql - “标量子查询产生了多个元素”
- node.js - mongoose populate() 函数是否为每个相关文档单独执行