[英]Apply function on each element of a list of matrices
I have a list of matrices. 我有一个矩阵列表。
(below is a simplified example, I actually have a list of 3 matrices, the first one being in 2D, while the second and third ones are in 3D) (下面是一个简化的示例,我实际上有3个矩阵的列表,第一个矩阵是2D的,而第二个和第三个矩阵是3D的)
> a <- matrix(-1:2, ncol = 2)
> b <- array(c(-2:5), dim=c(2, 2, 2))
> c_list <- list(a,b)
> c_list
[[1]]
[,1] [,2]
[1,] -1 1
[2,] 0 2
[[2]]
, , 1
[,1] [,2]
[1,] -2 0
[2,] -1 1
, , 2
[,1] [,2]
[1,] 2 4
[2,] 3 5
I'd like to apply the function max(0,c_list) to each and every element (without a loop), in order to have the same type of object as "c_list" but with the negative values replaced by zeros. 我想将函数max(0,c_list)应用于每个元素(无循环),以便与“ c_list”具有相同类型的对象,但负值替换为零。
> output
[[1]]
[,1] [,2]
[1,] 0 1
[2,] 0 2
[[2]]
, , 1
[,1] [,2]
[1,] 0 0
[2,] 0 1
, , 2
[,1] [,2]
[1,] 2 4
[2,] 3 5
I've managed to do it for a matrice or for a list with mapply or lapply, but not for a list of matrices. 我已经成功地针对矩阵或具有mapply或lapply的列表进行了此操作,但没有针对矩阵列表进行此操作。
Answer : either Sotos' answer 答案:索托斯的答案
output <- lapply(c_list, function(i)replace(i, i < 0, 0))
or Moody_Mudskipper's answer 或Moody_Mudskipper的答案
output <- lapply(c_list,pmax,0)
Using apply
and lapply
: 使用apply
和lapply
:
a <- matrix(-1:2, ncol = 2)
b <- matrix(-3:0, ncol = 2)
c <- list(a,b)
d <- lapply(c, function(m) {
apply(m, c(1, 2), function(x) max(0, x))
})
Output: 输出:
> d
[[1]]
[,1] [,2]
[1,] 0 1
[2,] 0 2
[[2]]
[,1] [,2]
[1,] 0 0
[2,] 0 0
您可以使用pmax
,它将保留源矩阵的格式并进行矢量化,比使用max
循环更快。
lapply(c_list,pmax,0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.