tidyeval函数和“ View()”问题

时间:2018-11-12 20:12:56

标签: r function dplyr tidyeval

除了行号14外,代码块#1和#2相同。代码块#1使用print()调用,代码块#2使用View()调用。代码块1可以正常工作。代码块2给出错误"Error in FUN(X[[i]], ...) : object 'cal.date' not found"。为什么?

1

library(tidyverse)
set.seed(1)
graph.data <- tibble(cal.date = as.Date(40100:40129, origin = "1899-12-30"), 
                     random_num = rnorm(30, 8, 5))

child_function <- function(df, variable, hor.line = 6) {  
  variable <- enquo(variable)
  df <- df %>% mutate(mutation = 2 * !!variable, horizontal.line = hor.line)
}

parent_function <- function(df, date, variable, hor.line = 6) {
  date <- enquo(date)
  variable <- enquo(variable)
  df <- df %>% child_function(!!variable, hor.line) %>% print()  # LINE 14
  p <- ggplot(df, aes(!!date, mutation)) + 
    geom_point() + 
    geom_hline(aes(yintercept = hor.line))
  p
}

parent_function(graph.data, date = cal.date, variable = random_num, hor.line = 8)

2

library(tidyverse)
set.seed(1)
graph.data <- tibble(cal.date = as.Date(40100:40129, origin = "1899-12-30"), 
                     random_num = rnorm(30, 8, 5))

child_function <- function(df, variable, hor.line = 6) {  
  variable <- enquo(variable)
  df <- df %>% mutate(mutation = 2 * !!variable, horizontal.line = hor.line)
}

parent_function <- function(df, date, variable, hor.line = 6) {
  date <- enquo(date)
  variable <- enquo(variable)
  df <- df %>% child_function(!!variable, hor.line) %>% View() # LINE 14
  p <- ggplot(df, aes(!!date, mutation)) + 
    geom_point() + 
    geom_hline(aes(yintercept = hor.line))
  p
}

parent_function(graph.data, date = cal.date, variable = random_num, hor.line = 8)

1 个答案:

答案 0 :(得分:5)

View()是一个副作用函数,不会返回任何内容

在第二种情况下,请使用%T>%软件包中的magrittr而不是%>%

View()结束了管道,因此您将希望拥有一个T pipe。我想您可以这样更清楚地看到它

 df %>% child_function(!!variable, hor.line) %>% View() -> df

vs。

 df %>% child_function(!!variable, hor.line) %T>% View() -> df