如何将函数调用的结果作为dplyr :: mutate的一部分展平?

天空步行者

我有以下简单的用例,其中定义了两个包含名称和位置的示例:

if(!require(tidyverse)) install.packages("tidyverse", repos = "http://cran.us.r-project.org")
if(!require(ggmap)) devtools::install_github("dkahle/ggmap")

# you may also need to 
#register_google(key="<register your own key>")

x <- tibble(name=c('a', 'b'), loc=c('china', 'switzerland'))
x
# A tibble: 2 x 2
   name  loc        
   <chr> <chr>      
1 a     china      
2 b     switzerland

现在,我想用经度和纬度信息来丰富我的小标题。我这样做是通过运行:

x %>% 
  mutate(lon=geocode(loc)$lon, lat=geocode(loc)$lat)

但这很昂贵,因为我需要每个样本两次调用该geocode函数,并且函数不是免费的。有没有办法使函数的返回变为平缓这是一次失败的尝试,并且是我要实现的目标的证明:geocode

x %>% 
  mutate(xx=geocode(loc), lon=xx$lon, lat=xx$lat)
>Error: Column `xx` is of unsupported class data.frame
卡米尔

对于添加地理编码坐标的特定情况,ggmap实际上有一个函数mutate_geocode可以完全做到这一点:

library(dplyr)
library(ggmap)

mutate_geocode(x, location = loc)
#> # A tibble: 2 x 4
#>   name  loc            lon   lat
#>   <chr> <chr>        <dbl> <dbl>
#> 1 a     china       104.    35.9
#> 2 b     switzerland   8.23  46.8

对于更一般的用途,purrr::map_*功能很好用。您可以映射位置名称,应用geocode,并取消嵌套该列表:

mutate(x, coords = purrr::map(loc, geocode)) %>%
  tidyr::unnest(coords)
# same output as above

您还可以使用提取所需的每一列purrr::map_dbl如果您返回的数据框不仅包含lon和lat列,那么这可能会很有用,例如,您将outputin设置为其他值geocode

mutate(x, coords = purrr::map(loc, geocode),
       lon = purrr::map_dbl(coords, "lon"),
       lat = purrr::map_dbl(coords, "lat"))
# same output as above

或按列位置:

mutate(x, coords = purrr::map(loc, geocode),
       lon = purrr::map_dbl(coords, 1),
       lat = purrr::map_dbl(coords, 2))
# same output

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章