Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I get "invalid 'type' (character) of argument" using xtab() in R

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading