Home > Back-end >  Unable to input string as function
Unable to input string as function

Time:09-13

I am trying to write a function which starts with filtering the dataset to only have one state when I run the function. I found [this answer][1] here which did not work for me.

example dataset here:

state <- sample(state.abb, size = 100, replace = TRUE)
registered <- sample(c("registered", "unregistered"), size = 100, replace = TRUE)

df <- data.frame(state, registered)

Function I wrote based on the example above:

create_xtab_tables <- function(state_name){
require(dplyr)
  
df2 <- 
  df %>% 
  filter(state == state_name)

return(df2)
}

when I run and try to input a state which is included in the datatable

df_ak <- create_xtab_tables(AK)

I get the following error:

Error in filter(): ! Problem while computing ..1 = state == state_name. Caused by error in mask$eval_all_filter(): ! object 'AK' not found Backtrace:

  1. global create_xtab_tables(AK)
  2. dplyr:::filter.data.frame(., state == state_name)
  3. dplyr:::filter_rows(.data, ..., caller_env = caller_env())
  4. dplyr:::filter_eval(dots, mask = mask, error_call = error_call)
  5. mask$eval_all_filter(dots, env_filter) [1]: string as function argument in R

CodePudding user response:

Here you pass a string. Therefore use quotation marks!

df_ak <- create_xtab_tables("AK")
  state registered
1    AK registered
2    AK registered
  • Related