Add all elements in matrix R

柔情痞子 提交于 2021-01-19 19:07:45

问题


I am trying to add all the elements in a matrix. This is an example of my matrix (the actual matrix is bigger):

 m = matrix(c(528,479,538,603),nrow=2,ncol=2)
 m
                   A            B
male              528          538
female            479          603

I am trying to do:

 sum.elements = colSums(colSums(m))

but it gives the following error:

Error in colSums(colSums(m)) : 'x' must be an array of at least two dimensions

I have tried doing:

x = colSums(m)
sum.elements = x[1] + x[2]

but this would be very long when you have a 100-column matrix...

Any help would be greatly appreciated!


回答1:


You can do sum. It also has the option na.rm to remove the NA values.

 sum(m)
 #[1] 2148

In general, sum works for vector, matrix and data.frame

Benchmarks

 set.seed(24)
 m1 <- matrix(sample(0:20, 5000*5000, replace=TRUE), ncol=5000)
 system.time(sum(m1))
 #  user  system elapsed 
 # 0.027   0.000   0.026 

 system.time(sum(colSums(m1)))
 # user  system elapsed 
 # 0.027   0.000   0.027 

 system.time(Reduce('+', m1))
 #  user  system elapsed 
 #25.977   0.644  26.673 



回答2:


Reduce will work

 Reduce(`+`,m)
    [1] 2148


来源:https://stackoverflow.com/questions/30277966/add-all-elements-in-matrix-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!