如何在另一个函数中传递/计算函数参数以与ggplot一起使用?

Mat*_*ert 5 eval r ggplot2

请考虑以下代码:

test <- function(x,n){

selection<-names(x)[n]
graph <- ggplot(x, aes(factor(selection)))
graph + geom_bar()
}

test(mtcars,1)
Run Code Online (Sandbox Code Playgroud)

它抛出错误导致R无法找到选择.我也玩过周围substitute,evalget没有成功.我发现了这个类似的问题,并且我认为我理解Joris'答案,但也不能对ggplot的参数使用相同的技巧.

koh*_*ske 9

你可以用它aes_string来达到这个目的.所以test应该是这样的:

test <- function(x,n){
  graph <- ggplot(x, aes_string(x = names(x)[n]))
  graph + geom_bar()
}
Run Code Online (Sandbox Code Playgroud)