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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With