Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error when using the apply function on a matrix in R

I’m trying to use apply to use the L1 norm on each column of a matrix in R. If we have a matrix

X=matrix(data=rnorm(100),nrow=10,ncol=10)

Then when I run

apply(X,2,function(x) norm(x,type="1"))

I get the error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error in base::norm(x, type, ...) : 'A' must be a numeric matrix

I’ve found that this is because when we index X, we lose the matrix type. For example, running

norm(X[,1],type="1")

we get the same error. Hence, I’ve run

  old <- `[`
`[` <- function(...) { old(..., drop=FALSE) }

To stop the matrix type being dropped when we subset X. Now, this works

norm(X[,1],type="1")

But I still get the same error for

apply(X,2,function(x) norm(x,type="1"))

>Solution :

You could do apply(X, 2, function(x) norm(matrix(x, ncol = 1), type = "1"), but you could also just do colSums(abs(X))–there’s not much point in using norm here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading