【问题标题】:Why do I get error with filter? Error in filter_impl(.data, quo) : Evaluation error: object not found为什么过滤器会出错? filter_impl(.data, quo) 中的错误:评估错误:找不到对象
【发布时间】:2019-07-27 13:15:04
【问题描述】:

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

这是我的数据框的样子:

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.

在函数之外,我的代码工作正常。

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

【问题讨论】:

    标签: r function filter dplyr


    【解决方案1】:

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

    你可以看看这个链接,非常非常有启发性: Programming with dplyr.

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

    • 在您的函数中,将输入转换为“quosure”:在函数开头插入:elt &lt;- enquo(elt)
    • x$statsx$boxplot 中,“整理评估”输入,将elt 替换为!! elt

    你也可以看看这个link,有有用的见解。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多