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

Apply() cannot be applied to this list?

I have created an example below, where I am trying to make a list of each row of a matrix, then use apply().

mat<-matrix(rexp(9, rate=.1), ncol=3)

my_list2 <- list()

for(i in 1:nrow(mat)) { 
  my_list2[[i]] <- mat[i,]
}

#DO NOT CHANGE THIS:
apply(my_list2[[i]],2,sum)

However the apply() function does not work, giving a dimension error. I understand that apply() is not the best function to use here but it is present in a function that I need so I cannot change that line.

Does anyone have any idea how I can change my "my_list2" to work better? Thank you!

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

Edit:

Here is an example that works (non reproducible)

Example

Note both the example above and this example have type "list"

>Solution :

This answer addresses "how to properly get a list of matrices", not how to resolve the use of apply.

By default in R, when you subset a matrix to a single column or a single row, it reduces the dimensionality. For instance,

mtx <- matrix(1:6, nrow = 2)
mtx
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    4    6
mtx[1,]
# [1] 1 3 5
mtx[,3]
# [1] 5 6

If you want a single row or column but to otherwise retain dimensionality, add the drop=FALSE argument to the [-subsetting:

mtx[1,,drop=FALSE]
#      [,1] [,2] [,3]
# [1,]    1    3    5
mtx[,3,drop=FALSE]
#      [,1]
# [1,]    5
# [2,]    6

In this way, your code to produce sample data can be adjusted to be:

set.seed(42) # important for reproducibility in questions on SO
mat<-matrix(rexp(9, rate=.1), ncol=3)

my_list2 <- list()
for(i in 1:nrow(mat)) { 
  my_list2[[i]] <- mat[i,,drop=FALSE]
}

my_list2
# [[1]]
#          [,1]     [,2]     [,3]
# [1,] 1.983368 0.381919 3.139846
# [[2]]
#          [,1]     [,2]     [,3]
# [1,] 6.608953 4.731766 4.101296
# [[3]]
#         [,1]     [,2]     [,3]
# [1,] 2.83491 14.63627 11.91598

And then you can use akrun’s most recent code to resolve how to get the row-wise sums within each list element, i.e., one of

lapply(my_list2, apply, 2, sum)
lapply(my_list2, function(z) apply(z, 2, sum))
lapply(my_list2, \(z) apply(z, 2, sum)) # R-4.1 or later
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