调用函数中的对象包裹在ggplot2-function

时间:2018-03-12 12:04:02

标签: r ggplot2

我即将编写一个函数来迭代各种变量的图。不幸的是我收到了一个我不明白的错误。

library(ggplot2)
library(dplyr)
library(purrr)

df <- data.frame(af = c(rep(1,6),rep(2,6),rep(3,6)), 
p = c(rep(c(rep("A",2),rep("B",2),rep("C",2)),3)), 
ele.1 = sample(c(1:100), size=6), 
ele.2 = sample(c(1:100), size=6), 
ele.3 = sample(c(1:100), size=6))


af p ele.1 ele.2 ele.3
1 A    99     1    68
1 A    55    38    72
1 B    70    36    13
1 B    86    77    89
1 C     7    24    49
1 C    89    23    53
2 A    99     1    68
2 A    55    38    72
....

test <- function(.x = df, .af = 1,.p=c("A","B"), .var = ele.1) {.x %>%
        filter(af == .af & p %in% .p) %>%
        ggplot(aes(x = .var, y = ele.2)) +
        geom_point() +
        geom_path()}


test(df)

这导致

**Error in FUN(X[[i]], ...) : object 'ele.1' not found
In addition: Warning message:
In FUN(X[[i]], ...) : restarting interrupted promise evaluation**

我怎么能在ggplot中调用对象ele.1扭曲该函数?

希望这不是另一个问题的改写。

欢呼声

1 个答案:

答案 0 :(得分:-1)

如果将.var参数设置为运行的字符。这是你在找什么?

test <- function(.x = df, .af = 1,.p=c("A","B"), .var = "ele.1") {
  .x %>%filter(af == .af & p %in% .p) 
  ggplot() +geom_point(aes(x = .x[[.var]], y = .x[["ele.2"]])) + geom_path()
  }

test(df)

enter image description here