I am trying to create a function that performs several statistical tests for specific columns in a data framework. Some of the tests require more than one level. I would like to check how many levels are in a particular column, but cannot seem to be correct.
In my actual code, this section will be followed by ifelse, which returns a string saying "only one level" if it is single, or continues the statistical test if> 1.
require("dplyr")
df <- data.frame(A = c("a", "b", "c"), B = c("a", "a", "a"), C = c("a", "b", "b")) %>%
mutate(A = factor(A)) %>%
mutate(B = factor(B)) %>%
mutate(C = factor(C))
my_funct <- function(data_f, column){
n_fact <- paste("data_f", column, sep = "$")
n_levels <- do.call("nlevels",
list(x = as.name(n_fact)))
print(n_levels)
}
`` ``
Then I call my function using dataframe and column
my_funct(df, "A")
I get the following error: Error in levels (x): object 'data_f $ A' not found
If I remove the as.name () wrapper, it will return the value 0.
Jason