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:
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"))
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.