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

Time:02-08

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)

I keep getting the same error:

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

I suspect there's some issue with the scoping of the function but no matter what combinations I try-- such as defining the tibble within the function or referencing the tibble directly within the function (as in, df$var) I still get an error.

CodePudding user response:

As we pass unquoted variable, use {{}} (curly-curly opertor) for evaluation

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

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

}

-testing

export_ids(wspid)

CodePudding user response:

I guess a better solution would be to simply use:

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")
  •  Tags:  
  • Related