alap
alap

Reputation: 647

Applying a function to a list of matrices

res_log <- lapply(res, log2)

res is a list and each element is a MATRIX. I get the error.

Error in match.fun(FUN) : '1' is not a function, character or symbol

Upvotes: 0

Views: 6113

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81743

If you want to calculate the base-2 logarithm of all values of the matrices in the list res, you can use the following command:

lapply(res, log2)

The command apply(res, 1, log2) will not work since a list has no rows. This can only be used with a single matrix object (or an array).

An example:

res <- rep(list(matrix(1:9, 3)), 2)

# [[1]]
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9
# 
# [[2]]
#       [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9


lapply(res, log2)

# [[1]]
#          [,1]     [,2]     [,3]
# [1,] 0.000000 2.000000 2.807355
# [2,] 1.000000 2.321928 3.000000
# [3,] 1.584963 2.584963 3.169925
# 
# [[2]]
#          [,1]     [,2]     [,3]
# [1,] 0.000000 2.000000 2.807355
# [2,] 1.000000 2.321928 3.000000
# [3,] 1.584963 2.584963 3.169925

Upvotes: 4

Related Questions