R applied does not work with matrix

I would like to know the reason why the following does not work on the matrix structure that I posted here (I used the dput command).

When I try to run:

apply(mymatrix, 2, sum) 

I get:

 Error in FUN(newX[, i], ...) : invalid 'type' (list) of argument 

However, when I check to make sure that it is a matrix, I get the following:

is.matrix (mymatrix)

 [1] TRUE 

I understand that I can get around this problem by canceling the data in the temp variable and then just re-creating the matrix, but I'm curious why this happens.

+4
source share
2 answers

?is.matrix says:

'is.matrix' returns 'TRUE' if 'x' is a vector and has a "dim" attribute of length 2) and "FALSE" otherwise.

Your object is a list with the dim attribute. A list is a type of vector (although it is not an atomic type that most people think of as vectors), therefore is.matrix returns TRUE . For instance:

 > l <- as.list(1:10) > dim(l) <- c(10,1) > is.matrix(l) [1] TRUE 

To convert mymatrix to an atomic matrix, you need to do something like this:

 mymatrix2 <- unlist(mymatrix, use.names=FALSE) dim(mymatrix2) <- dim(mymatrix) # now your apply call will work apply(mymatrix2, 2, sum) # but you should really use (if you're really just summing columns) colSums(mymatrix2) 
+5
source

The elements of your matrix are not numeric ; instead, they are list to see this:

 apply(m,2, class) # here m is your matrix 

So, if you need the sum of the column, you have to "force" them to numeric , and then apply colSums , which is the shortcut for apply(x, 2, sum)

 colSums(apply(m, 2, as.numeric)) # this will give you the sum you want. 
+5
source

Source: https://habr.com/ru/post/1434903/


All Articles