I have a sublist of principal component rotation vectors computed by prcomp
, where each list item is an Nx2
array (i.e., two column vectors), for each class.
我有一个由prcomp计算的主分量旋转矢量的子列表,其中每个列表项是每个类的Nx2数组(即两个列向量)。
Using those vectors, I'd like to project some data similarly structured into a list of classes, each class item containing arrays with dimension NxMxT
, where T
is the number of trials.
使用这些向量,我想将类似结构的一些数据投影到类列表中,每个类项包含具有维度NxMxT的数组,其中T是试验次数。
My problem is, I can write simple vectorized functions with apply
and its variants, but I'm having trouble generalizing this to apply that over each list.
我的问题是,我可以使用apply及其变体编写简单的向量化函数,但是我很难将其概括为将其应用于每个列表。
Example data:
示例数据:
somedata <- list(array(rnorm(100),dim=c(5,4,5)),array(rnorm(100),dim=c(5,4,5)))
somevectors <- list(array(rnorm(10),dim=c(5,2)),array(rnorm(10),dim=c(5,2)))
Here is a simple example of the operation over each list element:
以下是对每个列表元素的操作的简单示例:
o.proj.1 <- apply(somedata[[1]],3,function(x){
t(somevectors[[1]]) %*% x
}) # returns an array where each projected trial is a column
I tried fitting this inside a call to lapply()
, but didn't find much success:
我尝试在调用lapply()时调整它,但没有找到太多成功:
lapply(somedata, y = somevectors, function(x,y){
apply(x,3,function(z){
t(y) %*% z
})
})
Error in t(y) %*% z : requires numeric/complex matrix/vector arguments
Basically my algorithm is to put the appropriate apply
type (here lapply
) around the more local function and remove the index that will be vectorized (here [[]]
). What am I missing?
基本上我的算法是在更多局部函数周围放置适当的apply类型(这里是lapply)并删除将被矢量化的索引(这里[[]])。我错过了什么?
1 个解决方案
#1
2
Of the *apply
family of functions, mapply
is the one to use when you want to loop simultaneously over two or more objects. Try:
在* apply系列函数中,当你想在两个或多个对象上同时循环时,mapply就是一个。尝试:
o.proj <- mapply(function(x,y){
apply(x,3,function(z){
t(y) %*% z
})
}, somedata, somevectors, SIMPLIFY = FALSE)
I suppose you will want to use SIMPLIFY = FALSE
to return a list, otherwise mapply
will attempt to simplify your output into an array, a little like sapply
does.
我想你会想要使用SIMPLIFY = FALSE来返回一个列表,否则mapply会尝试将输出简化为数组,有点像sapply。
Also know that you can use Map
as a shortcut for mapply(..., SIMPLIFY = FALSE)
.
还要知道您可以使用Map作为mapply的快捷方式(...,SIMPLIFY = FALSE)。
#1
2
Of the *apply
family of functions, mapply
is the one to use when you want to loop simultaneously over two or more objects. Try:
在* apply系列函数中,当你想在两个或多个对象上同时循环时,mapply就是一个。尝试:
o.proj <- mapply(function(x,y){
apply(x,3,function(z){
t(y) %*% z
})
}, somedata, somevectors, SIMPLIFY = FALSE)
I suppose you will want to use SIMPLIFY = FALSE
to return a list, otherwise mapply
will attempt to simplify your output into an array, a little like sapply
does.
我想你会想要使用SIMPLIFY = FALSE来返回一个列表,否则mapply会尝试将输出简化为数组,有点像sapply。
Also know that you can use Map
as a shortcut for mapply(..., SIMPLIFY = FALSE)
.
还要知道您可以使用Map作为mapply的快捷方式(...,SIMPLIFY = FALSE)。