Use nlevels()
to count the levels in a factor.
Can you also share what you've tried for adding an else
to the checks? It's hard to help fix a problem with code we haven't seen.
This is just a "best practices" note: replace class(df[,variable])=='integer'
with is.integer(df[, variable])
. Some objects can have multiple classes, which would mess up your code. There's a similar function for factors.
P.S.: I formatted your code for the forum to make it easier to read. Check out FAQ: How to format your code to see how it's done.