R-为什么过滤器会出现错误?Filter_impl(.data,quo)中的错误:评估错误:找不到对象



我正在尝试编写一个函数,该函数可以自动化一些我想在数据框架的不同变量上进行的计算。

这是我的数据框架看起来像:

head(SoilGeology, n=5)  
# A tibble: 5 x 12
  Year  Zone            SubZone         Au_ppm Ag_ppm Cu_ppm Pb_ppm Zn_ppm As_ppm Sb_ppm Bi_ppm Mo_ppm
  <chr> <chr>           <chr>            <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 1990  BugLake         BugLake          0.007    3.7     17     27     23      1      1     NA      1
2 1983  Johnny Mountain Johnny Mountain  0.01     1.6     71     63    550      4     NA     NA     NA
3 1983  Khyber Pass     Khyber Pass      0.12    11.5    275    204   8230    178      7     60     NA
4 1987  Chebry          Ridge Line Grid  0.05     2.2     35     21    105     16      6     NA     NA
5 1987  Chebry          Handel Grid      0.004    1.3     29     27    663     45      2     NA     NA

我写的功能看起来像这样:

library(dplyr)
my_function <- function(df, st, elt){  
# df = data frame, str = element in string form, elt = element
  # tests
  if(!is.data.frame(df)){
    print("The table is not a data frame.")
    return(NULL)}  
  if(!is.character(st)){
     print('st is not in string form.')
     return(NULL)}
  if(!(st %in% colnames(df))){ 
    print("The element is not in the data frame.")
    return(NULL)}
  x <- list() # create our output list
  # Summary statistics
  x$stat <- df %>%
    filter(!is.na(elt)) %>%
    group_by(Year, Zone, SubZone) %>%
    summarise(
      n = sum(!is.na(elt)),
      min = min(elt),
      max = max(elt),
      mean = mean(elt),
      sd = sd(elt))
  # Boxplot
  x$boxplot <- df %>%
    group_by(Year, Zone, SubZone) %>%
    filter(n() > 40 & !is.na(elt)) %>%
    ggplot(df, mapping = aes(Zone, elt, color = Year)) +
    geom_boxplot() +
    scale_y_log10() +
    coord_flip()
  return(x)
}

我写

时会出现以下错误
Ag <- summary_statistics(SoilGeology,'Ag_ppm', Ag_ppm)
Error in filter_impl(.data, quo) : 
  Evaluation error: object 'Ag_ppm' not found.

在功能之外,我的代码工作正常。

关于为什么我的功能不起作用的任何见解?

问题可能是因为 dplyr中的非标准评估(NSE)

您可以查看此链接,非常有启发性:用dplyr。

编程

您情况的简短答案(应该有效):

  • 在您的功能中,将输入转换为" Quosure":函数开头插入:elt <- enquo(elt)
  • x$statsx$boxplot中," tidy-evaluate"输入,通过 !! elt
  • 替换elt

您也可以查看此链接,该链接具有有用的见解。

相关内容

最新更新