【问题标题】:tidyeval functions and problems with `View()`tidyeval 函数和 `View()` 的问题
【发布时间】:2018-11-12 20:12:56
【问题描述】:

代码块 #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)

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)

【问题讨论】:

    标签: r function dplyr tidyeval


    【解决方案1】:

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

    在您的第二种情况下,使用 magrittr 包中的 %T&gt;% 而不是 %&gt;%

    View() 结束管道,这样你就会想要一个 T pipe 代替。我想你可以像这样看得更清楚

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

    对比

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

    【讨论】:

    • 我认为这需要一个明确的library(magrittr)
    • @CalumYou,你是对的!我总是忘记tidyverse 没有加载它
    • 是的,这有点烦人,但 magrittr 与其他 tidyverse 函数(extract、set_names)有名称冲突。我希望他们在某个时候重命名一个或另一个,因为拥有 T 和分配管道很好
    猜你喜欢
    • 2019-04-20
    • 2019-04-15
    • 2019-09-26
    • 2018-11-01
    • 2019-05-06
    • 1970-01-01
    • 2020-02-13
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多