Changing a class from character to another type supporting rowSums in r

I have a matrix with: character elements.

sapply(mat,class) "character" 

I would like to apply rowSums to this matrix, but I get an error:

 Error in rowSums(mat) : 'x' must be numeric 

If I do as.numeric (mat), then I get a vector.

Is there a way to change from character to numeric, but keep the matrix structure?

+4
source share
1 answer

You can change the storage mode of your matrix:

 mmat <- matrix(c("2","3","7","0"), ncol = 2) storage.mode(mmat) <- "double" # changed from "numeric" rowSums(mmat) # [1] 9 3 
+8
source

All Articles