1

I have the following code:

install.packages('tidyverse')
library(tidyverse)
x <- 1:10
y <- x^2
df <- data.frame(first_column = x, second_column = y)
tibble <- as_tibble(df)

tibble %>% 
  filter(second_column != 16) %>%
  ggplot(aes(x = first_column, y = second_column)) + 
  geom_line()

Now I would like to create the following function

test <- function(colname) {
  tibble %>% 
    filter(colname != 16) %>%
    ggplot(aes(x = first_column, y = colname)) + 
    geom_line()
}

test('second_column')

But running it creates a vertical line instead of the function. How can I make this function work? Edit: My focus is on getting the pipe to work, not ggplot.

Dutchmv
  • 126
  • 7
  • Try using `aes_string(x = "first_column", y = colname)` – Benjamin Apr 03 '17 at 10:58
  • Possible duplicate of [R pass variable column indices to ggplot2](http://stackoverflow.com/questions/15458526/r-pass-variable-column-indices-to-ggplot2) – Benjamin Apr 03 '17 at 11:00
  • Possible duplicate of [Addressing x and y in aes by variable number](http://stackoverflow.com/questions/15323269/addressing-x-and-y-in-aes-by-variable-number) – JanLauGe Apr 03 '17 at 11:02
  • aes_string works for ggplot, but my problem of variable column names in the pipe remanes. – Dutchmv Apr 03 '17 at 11:16
  • Subset by name-of-column is easy using base R: `tibble[tibble[[colname]] != 16,]` – Spacedman Apr 03 '17 at 11:30
  • 2
    Note if the focus is on getting the filter to work then construct an example that works without needing `ggplot2`, then people without `ggplot2` installed can also help you. – Spacedman Apr 03 '17 at 11:42

1 Answers1

1

In order to pass character strings for variable names, you have to use the standard evaluation version of each function. It is aes_string for aes, and filter_ for filter. See the NSE vignette for more details.

Your function could look like:

test <- function(colname) {
  tibble %>% 
    filter_(.dots= paste0(colname, "!= 16")) %>%
    ggplot(aes_string(x = "first_column", y = colname)) + 
    geom_line()
}
jlesuffleur
  • 1,113
  • 1
  • 7
  • 19