Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing class from 'character' to other type which supports rowSums in r

Tags:

r

I have a matrix with: character class entries.

sapply(mat,class)
"character"

I would like to apply rowSums to this matrix but I get the 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?

like image 213
user1723765 Avatar asked Feb 18 '23 23:02

user1723765


1 Answers

You could 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
like image 64
BenBarnes Avatar answered Mar 30 '23 01:03

BenBarnes