将功能应用于两个列表?

时间:2021-05-03 18:36:37

To find the row-wise correlation of two matrices A(=X) and B(=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):

为了找到两个矩阵A(= X)和B(= Y)的行方向相关性,输出应该具有X的行1和Y的行1的相关值,...因此总共十个值(因为有十行):

X <- matrix(rnorm(2000), nrow=10)
Y <- matrix(rnorm(2000), nrow=10)

sapply(1:10, function(row) cor(X[row,], Y[row,]))

Now, how should I apply this function to two lists (containing around 50 dataframes each)?

现在,我应该如何将此函数应用于两个列表(每个包含大约50个数据帧)?

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.

考虑列表A具有数据帧$ 1,$ 2,$ 3 ......等等,列表B具有相似数量的数据帧$ 1,$ 2,$ 3。所以该函数应该应用于listA $ 1,listB $ 1和listA $ 2,listB $ 2 ......等等,列表中的其他数据帧。最后,在比较1(listA $ 1和listB $ 1)的情况下,我将有10个值,对于其他人也是如此。

Could this be done using "lapply"?

这可以用“lapply”来完成吗?

1 个解决方案

#1


29  

You seem to be looking for mapply. Here's an example:

你似乎在寻找mapply。这是一个例子:

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)

#1


29  

You seem to be looking for mapply. Here's an example:

你似乎在寻找mapply。这是一个例子:

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)