Reputation: 547
I have this matrix mat=matrix(rnorm(15), 1, 15)
[1x15] and I want to use the function apply
to calculate the sum of rows in matix mat
e.g.
[,1] [,2] [,3] [,4]
[1,] 1 2 3 0 #the sum is then 6
Here is my code:
mat=matrix(rnorm(15), 1, 15)
apply(mat[,1:15],1,sum)
Here is the error: Error in apply(mat[, 1:15], 1, sum) : dim(X) must have a positive length
If I create two or more rows the apply
function works.
e.g.
mat=matrix(rnorm(15), 2, 15)
apply(mat[,1:15],1,sum) #this will work
What should I change to the function so it would work even for matrices with one row?
Upvotes: 0
Views: 1626
Reputation: 1
create a matrix and use general apply formulation: matrix =m, MARGIN = 1 (for row),2(for column), and FUN = sum.
m=matrix(1:9,3,3)
apply(m,1,sum)
Upvotes: 0
Reputation: 263499
Do this instead and then go read the ?Extract
help page. That page has a wealth of information about the most fundamental functions of R, namely "[" and "[[".
apply(mat[ ,1:15, drop=FALSE],1,sum) # preserves the matrix class
[1] -1.621488
Upvotes: 2
Reputation: 2216
The problem is that when you call the elements 1 to 15 you are converting your matrix to a vector so it doesn't have any dimension. just using the as.matrix
in the apply call will make it work.
mat=matrix(rnorm(15), 1, 15)
apply(as.matrix(mat[,1:15]),2,sum)
Upvotes: 2