将函数应用于两个列表? [英] Applying a function to two lists?

查看:31
本文介绍了将函数应用于两个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要找到两个矩阵 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$1listA$2,listB$2 ... 等列表中的其他数据帧.最后,在比较 1(listA$1listB$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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆