我想创建一个函数,该函数采用简单的要素图层和变量名称,并根据变量值创建随机点。我可以使用管道(%)按顺序执行此操作而不会出现问题,但我一直坚持使用管道设置功能来做同样的事情。
library(tidyverse)
library(sf)
library(tmap)
data("World") # load World sf dataset from tmap
# this works to create a point layer of population by country
World_pts <- World %>%
select(pop_est) %>%
filter(pop_est >= (10^6)) %>%
st_sample(., size = round(.$pop_est/(10^6))) %>% # create 1 random point for every 1 million people
st_sf(.)
# here's what it looks like
tm_shape(World) + tm_borders() + tm_shape(World_pts) + tm_dots()
# this function to do the same does not work
pop2points <- function(sf, x){
x <- enquo(x)
sf %>%
select(!!x) %>%
filter(!!x >= (10^6)) %>% # works up to here
st_sample(., size = round(!!.$x/(10^6))) %>% # this is where it breaks
st_sf(.)
}
World_pts <- pop2points(World,pop_est)
我怀疑我对如何处理函数参数中的非标准评估感到困惑。