Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force "apply" to return a matrix?

Tags:

r

Suppose I have a data matrix and I want to first center the matrix by row and then calculate the mean by column.

a=matrix(runif(50),nrow=5)
a1=apply(a,1,function(x)x-mean(x))
a.sum=apply(a1,1,sum)

This works well when a has multiple columns. However, sometimes the input has only one column and that will cause trouble:

a=matrix(runif(5))
a1=apply(a,1,function(x)x-mean(x))
a.sum=apply(a1,1,sum)
Error in apply(a1, 1, sum) : dim(X) must have a positive length

This is because the first apply returned a vector, not a matrix. R automatically dropped the dimension. So is there a clever way to prevent this? I know I can use if to detective the dimension of a and process that with different coding. But that seems a bit awkward.

like image 710
user2950937 Avatar asked Oct 30 '15 07:10

user2950937


1 Answers

Just tell R it's a matrix:

a=matrix(runif(5))
#          [,1]
#[1,] 0.0103764
#[2,] 0.9738857
#[3,] 0.2845688
#[4,] 0.7050949
#[5,] 0.3000554

a1=as.matrix(apply(a,1,function(x)x-mean(x)))
#     [,1]
#[1,]    0
#[2,]    0
#[3,]    0
#[4,]    0
#[5,]    0

a.sum=apply(a1,1,sum)
#[1] 0 0 0 0 0
like image 169
Andre Wildberg Avatar answered Sep 28 '22 20:09

Andre Wildberg