The error…
Error in FUN(X[[i]], ...) : invalid 'type' (character) of argument
…is not new and I can find a lot of SO questions about it. But because of low quality MWE’s I’m not able to fit the answers to my own problem.
I’m interested not only in a quick code based solution but in a deeper understand why this error happens.
set.seed(0)
df <- data.frame(
gender = sample(c("female", "male"), 100, replace = TRUE),
foo = sample(c(TRUE, FALSE), 100, replace = TRUE),
bar = sample(c(0, 1, 2, 3, 4), 100, replace = TRUE)
)
xtabs(gender ~ foo, data=df)
>Solution :
The left hand side of the formula is usually empty. If you have something there, it should be a vector or matrix of counts. You have gender there, which is a character variable and the error message comes when xtabs() tries to interpret it as counts.
So to fix this, just put the two factors on the right hand side:
xtabs(~ gender + foo, data=df)
BTW, even though neither one of those columns is actually a "factor", xtabs() will automatically convert them.