将功能应用到两个列表? [英] Applying a function to two lists?
问题描述
要找到两个矩阵X和Y的按行相关,输出应具有X的第1行和Y的第1行的相关值,因此,总共有十个值(因为有十行):
To find the row-wise correlation of two matrices X and Y, the output should have a correlation value for row 1 of X and row 1 of Y, ..., hence in total ten values (because there are ten rows):
X <- matrix(rnorm(2000), nrow=10)
Y <- matrix(rnorm(2000), nrow=10)
sapply(1:10, function(row) cor(X[row,], Y[row,]))
现在,我应该如何将此功能应用于两个列表(每个列表包含大约50个数据框)?
考虑列表A具有数据帧$ 1,$ 2,$ 3 ...,依此类推,列表B具有类似数量的数据帧$ 1,$ 2,$ 3.因此,该函数应应用于listA$1,listB$1
和listA$2,listB$2
...,以此类推,以用于列表中的其他数据帧.最后,在比较1的情况下(listA$1
和listB$1
),对于其他情况,我将有十个值.
Consider list A has dataframes $1, $2, $3... and so on and list B has similar number of dataframes $1, $2, $3. So the function should be applied to listA$1,listB$1
and listA$2,listB$2
... and so on for other dataframes in the list. In the end I will have ten values in case of comparison 1 (listA$1
and listB$1
) and for others as well.
可以使用"lapply"完成此操作吗?
Could this be done using "lapply"?
推荐答案
您似乎正在寻找mapply
.这是一个示例:
You seem to be looking for mapply
. Here's an example:
listA <- list(matrix(rnorm(2000), nrow=10),
matrix(rnorm(2000), nrow=10))
listB <- list(matrix(rnorm(2000), nrow=10),
matrix(rnorm(2000), nrow=10))
mapply(function(X,Y) {
sapply(1:10, function(row) cor(X[row,], Y[row,]))
}, X=listA, Y=listB)
这篇关于将功能应用到两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!