【问题标题】:R: Passing Column Names to Function w/ dplyrR:使用 dplyr 将列名传递给函数
【发布时间】:2017-08-22 19:18:00
【问题描述】:

我正在尝试在 R 中设置一个函数,以准备特定格式的数据以输入相关图。在处理数据集时,我倾向于使用 dplyr,因为它清晰且易于使用,但在使用 dplyr 时尝试将数据集和指定的列名传递给此函数时遇到了问题。

这是设置,为了清楚起见,包括在此处(略微缩写形式)。我没有遇到任何错误,在发布之前我确认 corrData 设置正确:

library(corrplot)
library(tidyverse)
library(stringr)

table2a <- table2 %>%
    mutate(example_index = str_c(country,year, sep="."))

这是实际的功能:

prepCorr <- function(dtable, x2, index2) { 

  practice <- dtable %>%
    select(index2, x2) %>%
    mutate(count=1) %>%
    complete(index2, x2)

  practice$count[is.na(practice$count)] <- 0

  practice <- spread(practice, key = x2, value = count)

  M <- cor(practice)
  return(M)
}

prepCorr(table2a, type, example_index)

每当我运行这个函数时,我都会得到:

Error in overscope_eval_next(overscope, expr) : object 'example_index' not found

我也尝试利用 quosures 来解决此问题,但这样做时会收到不同的错误。当我运行以下修改后的代码时:

prepCorr <- function(dtable, x2, index2) { 
  x2 <- enquo(x2)
  index2 <- enquo(index2)

  practice <- dtable %>%
    select(!!index2, !!x2) %>%
    mutate(count=1) %>%
    complete(!!index2, !!x2)

  practice$count[is.na(practice$count)] <- 0

  practice <- spread(practice, key = !!x2, value = count)

  return(cor(practice))
}

prepCorr(table2a, type, example_index)

我明白了:

Error in !index2 : invalid argument type 

我在这里做错了什么,我该如何解决这个问题?我相信我正在使用 dplyr 0.7 进行澄清。

更新:用可重现的示例替换旧示例。

【问题讨论】:

  • 你能发一个reproducible example吗?
  • 如果我编辑问题以使用 tidyverse 包中的 table2 而不是此处显示的表格,可以吗?它应该很好地用于此目的。
  • 当然,只要它给出相同的错误,我们可以用它来“调试”
  • 好的,现在应该可以重现了,谢谢指点。
  • 保存 RStudio 以解决 RStudio 特定的问题。 (RStudio 界面,或在 RGui 或 R 命令行中工作的代码,但不在 RStudio 中。)

标签: r dplyr


【解决方案1】:

看看这个例子

library(dplyr)
myfun <- function(df, col1, col2) {
              col1 <- enquo(col1)     # need to quote
              col2 <- enquo(col2)
              df1 <- df %>%
                       select(!!col1, !!col2)   #!! unquotes
              return(df1)
         }

myfun(mtcars, cyl, gear)

你可以在这里link了解更多关于NSESE的信息

【讨论】:

  • 当我运行它时,使用说 index2
  • 我使用了双感叹号,但奇怪的是错误只返回 !index2 而不是 !!index2
  • 看起来在tidyr::complete 上失败了。您应该问一个单独的问题,看看是否可以使用 tidyr::completetidyr::spread 进行 NSE 评估
  • 如果我只使用 tidyr::select 会失败,并且在 tidyr::spread 被处理之前它会失败(或者如果我注释 tidyr::spread 并且只测试第一个 tidyr 代码块)
  • 它似乎将 !!index2 处理为 !(!index2)。我可以避免吗?
猜你喜欢
  • 2021-01-19
  • 2017-09-12
  • 1970-01-01
  • 2015-04-04
  • 2018-05-09
  • 2023-03-31
  • 2017-09-14
  • 2021-08-16
  • 2018-03-18
相关资源
最近更新 更多