Search code examples
rloopssapply

Trying to use loop to find unique variables in a dataset and use sapply to apply a certain function


I am trying to use a loop to find the unique variables in an NHANES dataset and use sapply to apply the function nhanes_uniq to the NHANES library. I keep getting an error, Here is the code:

library(NHANES)
nhanes_uniq <- vector("integer", ncol(NHANES))
names(nhanes_uniq) <- names(NHANES)
for (i in names(NHANES)) {
  nhanes_uniq[i] <- n_distinct(NHANES[[i]])
}
sapply(NHANES[,ind], nhanes_uniq)

Here is the error:

Error in get(as.character(FUN), mode = "function", envir = envir) : object 'nhanes_uniq' of mode 'function' was not found

Solution

  • this might solve your problem

    names(NHANES)[sapply(NHANES, is.factor)]
    

    sapply(NHANES, is.factor) to get a logical vector for of the columns that are factors. use it as a subset to get the names of the factor vars.