tidyeval函数和`View()`的问题

sta*_*tor 1 r function dplyr tidyeval

代码块#1和#2是相同的,除了行号14.代码块#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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

Jra*_*u56 5

View()是副作用功能,不返回任何东西.

使用%T>%magrittr包装,而不是%>%你的第二个案例.

View()结束管道,以便你想要一个T pipe代替.我想你可以更清楚地看到它

 df %>% child_function(!!variable, hor.line) %>% View() -> df
Run Code Online (Sandbox Code Playgroud)

 df %>% child_function(!!variable, hor.line) %T>% View() -> df
Run Code Online (Sandbox Code Playgroud)

  • 是的,它有点烦人但是magrittr与其他整数函数(extract,set_names)有名称冲突.我希望他们在某个时候重命名,因为T和赋值管道很好 (2认同)