This is a test version of Biostars. For the public version, visit https://www.biostars.org.
apply function error

I have this dataframe and when i'm trying to count sum of columns I'm getting this error message:

 Error in FUN(X[[i]], ...) : invalid 'type' (character) of argument.
apply r

try this:

data |>
    apply(2, as.numeric) |>
    colSums()

2 answers

It's telling you that one or more of your columns is formatted as a character instead of numeric, so you need to convert them first.

data[] <- lapply(data, as.numeric)

If you're curious which columns are characters.

colnames(data[, sapply(data, is, "character")])

And FWIW, if you've fixed the type problem, there is a function for summing columns called colSums().

the error invalid 'type' (character) is telling you that the information in the cells of your data frame are characters (i.e. text) not numbers (aka numerics). R can be picky about the "type" and in this case since you can't sum letters you get this error.

First convert your data.frame columns to numerics, one option is:

df <- apply(df, 2, function(x) as.numeric(x))
sums <- apply(df, 2, sum)

though personally I tend to go with colSums for this sort of operation.

Log in to answer this question.