【发布时间】:2021-04-08 15:56:39
【问题描述】:
我编写了一个函数来制作散点图,该函数允许用户输入点的大小作为数值(保留在 aes() 调用之外)或作为数据框中的变量被映射(需要进入aes() 调用)。我远不是 NSE 方面的专家,虽然我已经开始工作了,但我觉得一定有更好的方法来做到这一点?
函数的简化版如下:
library(tidyverse)
data <- tibble(x = 1:10, y = 1:10)
test_func <- function(data, variable = 6){
# capture the variable in vars (I think quote would also work in this function)
variable <- vars({{variable}})
# convert it to a string and check if the string starts with a digit
# i.e. checking if this is a simple point size declaration not an aes mapping
is_number <- variable[[1]] %>%
rlang::as_label() %>%
str_detect("^[:digit:]*$")
# make initial ggplot object
p <- ggplot(data, aes(x = x, y = y))
# if variable is a simple number, add geom_point with no aes mapping
if(is_number){
variable <- variable[[1]] %>%
rlang::as_label() %>%
as.numeric()
p <- p + geom_point(size = variable)
} else{
# otherwise it must be intended as an aes mapping variable
variable <- variable[[1]] %>%
rlang::as_label()
p <- p + geom_point(aes(size = .data[[variable]]))
}
p
}
# works as a number
test_func(data, 10)
# works as a variable
test_func(data, y)
由reprex package (v2.0.0) 于 2021-04-08 创建
【问题讨论】: