Home > database >  Apply() cannot be applied to this list?
Apply() cannot be applied to this list?

Time:03-19

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!

Edit:

Here is an example that works (non reproducible)

Example

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

CodePudding user response:

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

CodePudding user response:

In your screenshot it works because the object part of the list ex[[1]] is an array. And in your example the elements of your list are vectors. You could try the following:

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

my_list2 <- list()

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

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

You should note that apply cannot be applied to all three elements of the array in one line. And to do it in one, that line should be changed.

  •  Tags:  
  • r
  • Related