我有一个对象列表。每个对象都有一个矩阵。我想对所有对象执行矩阵求和。目前,我通过结合" Reduce"和" lapply",其中lapply采用从每个对象中提取矩阵的函数。
有更有效的方法来实现这个吗?
虚拟例子:
mat_1 = matrix(data = c(rep(0.01,4),rep(0.29,4)), nrow = 4, ncol = 2)
mat_2 = matrix(data = c(rep(0.1,4),rep(0.2,4)), nrow = 4, ncol = 2)
obj_1 = list(name = "obj1", my_mat = mat_1) class(obj_1) = "my_obj"
obj_2 = list(name = "obj2", my_mat = mat_2) class(obj_2) = "my_obj"
list_of_my_objs = list(obj_1,obj_2)
get_mat_from_obj = function(my_obj) {
return(my_obj$my_mat)
}
Reduce('+', lapply(list_of_my_objs,get_mat_from_obj))