我的 user-defined 函数出现 'not found' 错误的原因是什么?

What is the cause of the 'not found' error in my user-defined function?

df <- tibble(wspid = c("text","text",1:9,NA),
             PID = c("text","text",1:10))

#Function to export a single column inputted in the function argument
export_ids <- function(var) {
  
  export_df <- df %>%
    filter(!is.na(var)) %>%
    select(var)

  write_csv(export_df, "~/Downloads/final_ids.csv")

}

#Calling the function
export_ids(wspid)

我不断收到同样的错误:

Error: Problem with `filter()` input `..1`.
ℹ Input `..1` is `!is.na(var)`.
x object 'wspid' not found

我怀疑函数的作用域存在一些问题,但无论我尝试什么组合——例如在函数内定义小标题或直接在函数内引用小标题(如 df$var)我仍然出现错误。

当我们传递未引用的变量时,使用 {{}}(curly-curly 运算符)进行评估

export_ids <- function(var) {
  
  export_df <- df %>%
    filter(!is.na({{var}})) %>%
    select({{var}})

  write_csv(export_df, "~/Downloads/final_ids.csv")

}

-测试

export_ids(wspid)

我想更好的解决方案是简单地使用:

df <- tibble(wspid = c("text","text",1:9,NA),
             PID = c("text","text",1:10))

#Function to export a single column inputted in the function argument
export_ids <- function(df, var) {
    data <- df[[var]]
    # now filter out NA values
    data <- data[!is.na(data)]
    write_csv(data, "~/Downloads/final_ids.csv")
}

#Calling the function
export_ids(df, "wspid")