0

I am about to write a function to iterate my plots over various variables. Unfortunately I am getting an error i don't understand.

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)

this results in

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

how could i call the object ele.1 in ggplot warped around that function?

hope this is no reword from another question.

cheers

Axeman
  • 32,068
  • 8
  • 81
  • 94
  • 1
    You can't just pass along variable names to `aes` like that. Have a look at `aes_` or `aes_string`. I agree that the error is not all that intuitive. – Axeman Mar 12 '18 at 12:22
  • E.g. `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() }` works. – Axeman Mar 12 '18 at 12:27

1 Answers1

-1

If you set .var argument as character it runs. Is this what you are looking for?

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

Antonios
  • 1,919
  • 1
  • 11
  • 18