I've got a big ~ 15,000 x 1,500 dataset that I've loaded in from an SPSS .sav file. Most of the variables are labeled, even the continuous ones. I'd like to take all variables that are clearly factors (i.e. the ones with only 0, 1, and NA values) and use the to_factor() function to turn them into factors. I've been trying to figure out a mutate_if() condition that would evaluate true for all variables with only (0, 1, NA) unique values, but I'm stuck.
library(tidyverse)
df <- tibble(X1 = rnorm(50), X2 = rnorm(50), X3 = rnorm(50),
X4 = sample(c(0,1), 50, replace = TRUE),
X5 = sample(c(0,1), 50, replace = TRUE),
X6 = rnorm(50), X7 = sample(c(0,1), 50, replace = TRUE))
# Here's a hacky way that I tried, doesn't work
df %>%
mutate_if(sum(unique(.), na.rm = TRUE) == 1, ~ as.factor(.x))