管道

时间:2017-04-03 10:56:02

标签: r dplyr

我有以下代码:

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()

现在我想创建以下功能

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

test('second_column')

但是运行它会创建一条垂直线而不是函数。如何使此功能起作用? 编辑:我的重点是让管道工作,而不是ggplot。

1 个答案:

答案 0 :(得分:1)

为了传递变量名的字符串,您必须使用每个函数的标准评估版本。 aes_stringaesfilter_filter。有关详细信息,请参阅NSE vignette

您的功能可能如下所示:

test <- function(colname) {
  tibble %>% 
    filter_(.dots= paste0(colname, "!= 16")) %>%
    ggplot(aes_string(x = "first_column", y = colname)) + 
    geom_line()
}
相关问题