apply function error
2
0
Entering edit mode
2.9 years ago
j_weld ▴ 10

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 • 2.5k views
ADD COMMENT
0
Entering edit mode

try this:

data |>
    apply(2, as.numeric) |>
    colSums()
ADD REPLY
2
Entering edit mode
2.9 years ago

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")])
ADD COMMENT
2
Entering edit mode

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

ADD REPLY
2
Entering edit mode
2.9 years ago
jv ★ 1.8k

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.

ADD COMMENT

Login before adding your answer.

Traffic: 1381 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6