[英]apply a function to multiple list with common elements in r
I have two list with multiple elements, I want to use these two list and apply a formula(function)我有两个包含多个元素的列表,我想使用这两个列表并应用公式(函数)
As an example, lets say, I have two list A and B with two elements x, and y (I have 1000's of elements, as an example lets say we have 2 elements x and y)例如,假设我有两个列表 A 和 B,其中包含两个元素 x 和 y(我有 1000 个元素,例如我们有 2 个元素 x 和 y)
listA <- list(x=matrix(rnorm(50), nrow=10),
y=matrix(rnorm(50), nrow=10))
listB <- list(x=matrix(rnorm(5), nrow=1),
y=matrix(rnorm(5), nrow=1))
for each row I need to apply the following fomualae for each row with same elements in listA and listB and save it in respective list as shown below for 2 rows for list x and y.对于每一行,我需要对 listA 和 listB 中具有相同元素的每一行应用以下公式,并将其保存在各自的列表中,如下所示,用于列表 x 和 y 的 2 行。 I need to repat this for all the rwos and multiple lists.
我需要为所有 rwos 和多个列表重新设置。
#For list X
# for row 1 listA
abs(listA$x[1,]-listB$x[1,])/(abs(listA$x[1,])+abs(listB$x[1,]))
# for row 2 listB
abs(listA$x[2,]-listB$x[1,])/(abs(listA$x[2,])+abs(listB$x[1,]))
#For list Y
# for row 1
abs(listA$y[1,]-listB$y[1,])/(abs(listA$y[1,])+abs(listB$y[1,]))
# for row 2
abs(listA$y[2,]-listB$y[1,])/(abs(listA$y[2,])+abs(listB$y[1,]))
I have been trying with lapply
and mapply
but not successful so far.我一直在尝试使用
lapply
和mapply
但到目前为止还没有成功。
One attempt using Map
and sweep
, which I think gives the intended result:使用
Map
和sweep
一次尝试,我认为这给出了预期的结果:
Map(function(x,y) abs(sweep(x,2,y,FUN="-"))/(sweep(abs(x),2,abs(y),FUN="+")),
listA,
listB)
Eg:例如:
listA <- list(x=matrix(1:9, nrow=3),
y=matrix(1:9, nrow=3))
listB <- list(x=matrix(1:3, nrow=1),
y=matrix(4:6, nrow=1))
Map(function(x,y) abs(sweep(x,2,y,FUN="-"))/(sweep(abs(x),2,abs(y),FUN="+")),
listA,
listB)
#$x
# [,1] [,2] [,3]
#[1,] 0.0000000 0.3333333 0.4000000
#[2,] 0.3333333 0.4285714 0.4545455
#[3,] 0.5000000 0.5000000 0.5000000
#
#$y
# [,1] [,2] [,3]
#[1,] 0.6000000 0.11111111 0.07692308
#[2,] 0.3333333 0.00000000 0.14285714
#[3,] 0.1428571 0.09090909 0.20000000
Matches the long-hand calculations:匹配长手计算:
abs(listA$x[1,]-listB$x[1,])/(abs(listA$x[1,])+abs(listB$x[1,]))
#[1] 0.0000000 0.3333333 0.4000000
abs(listA$x[2,]-listB$x[1,])/(abs(listA$x[2,])+abs(listB$x[1,]))
#[1] 0.3333333 0.4285714 0.4545455
abs(listA$y[1,]-listB$y[1,])/(abs(listA$y[1,])+abs(listB$y[1,]))
#[1] 0.60000000 0.11111111 0.07692308
abs(listA$y[2,]-listB$y[1,])/(abs(listA$y[2,])+abs(listB$y[1,]))
#[1] 0.3333333 0.0000000 0.1428571
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.