Ras*_*oul 4 r function ggplot2
我正在使用 gapminder 并尝试编写一个简单的函数来显示lifeExp对gdpPercap. 但是,当我将参数放入函数中时,无法识别参数。
我已经尝试了几个答案,但还没有结果。
plotting <- function (input, xx, yy){
library (ggplot2)
library (gapminder)
ggplot (input, aes (xx, yy, size = pop, color = country)) + geom_point(show.legend = FALSE)
}
Run Code Online (Sandbox Code Playgroud)
当运行plotting (gampinder, lifeExp, gdpPercap)被用作输入,xx并且yy,其结果是
“FUN(X[[i]], ...) 中的错误:找不到对象‘gdpPercap’”`
这是我被卡住的地方,gdpPercap在那里但没有被代码找到!能否请你帮忙。
你需要在里面使用tidy 评估aes()。无论是.data[[ ]]或{{ }}(卷曲卷曲)会工作。另请参阅Hadley Wickham 的 Advanced R 书中的此答案和Tidy 评估部分。
library(gapminder)
library(rlang)
library(ggplot2)
plotting <- function(input, xx, yy) {
ggplot(input, aes(.data[[xx]], .data[[yy]], size = pop, color = country)) +
geom_point(show.legend = FALSE)
}
plotting(gapminder, "lifeExp", "gdpPercap")
Run Code Online (Sandbox Code Playgroud)

plotting2 <- function(input, xx, yy) {
ggplot(input, aes({{xx}}, {{yy}}, size = pop, color = country)) +
geom_point(show.legend = FALSE)
}
plotting2(gapminder, lifeExp, gdpPercap)
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2019 年 11 月 9 日创建