如何使用管道 (%) 将变量名称传递给函数中的 st_sample() 参数?
How do I pass a variable name to st_sample() argument in a function using pipes (%)?
我想创建一个函数,它接受一个简单的要素层和一个变量名,并根据变量值创建随机点。我可以按顺序使用管道 (%) 毫无问题地执行此操作,但我在使用管道设置函数时遇到了同样的问题。
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)
我怀疑我对如何处理函数参数中的非标准求值感到困惑。
一个选项是将您的 x
转换为标签并使用 .[[
方法来引用列名:
pop2points <- function(sf, x){
x <- enquo(x)
sf %>%
select(!!x) %>%
filter(!!x >= (10^6)) %>%
st_sample(., size = round(.[[as_label(x)]] /(10^6))) %>%
st_sf(.)
}
我想创建一个函数,它接受一个简单的要素层和一个变量名,并根据变量值创建随机点。我可以按顺序使用管道 (%) 毫无问题地执行此操作,但我在使用管道设置函数时遇到了同样的问题。
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)
我怀疑我对如何处理函数参数中的非标准求值感到困惑。
一个选项是将您的 x
转换为标签并使用 .[[
方法来引用列名:
pop2points <- function(sf, x){
x <- enquo(x)
sf %>%
select(!!x) %>%
filter(!!x >= (10^6)) %>%
st_sample(., size = round(.[[as_label(x)]] /(10^6))) %>%
st_sf(.)
}