【问题标题】:apply a function to multiple list with common elements in r将函数应用于具有 r 中公共元素的多个列表
【发布时间】:2015-02-09 07:20:24
【问题描述】:

我有两个包含多个元素的列表,我想使用这两个列表并应用一个公式(函数)

例如,假设我有两个列表 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))

对于每一行,我需要为 listA 和 listB 中具有相同元素的每一行应用以下公式,并将其保存在相应的列表中,如下所示,对于列表 x 和 y 的 2 行。我需要为所有 rwo 和多个列表重新分配此内容。

#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,]))

我一直在尝试使用lapplymapply,但到目前为止还没有成功。

【问题讨论】:

    标签: r lapply sapply


    【解决方案1】:

    使用Mapsweep 的一次尝试,我认为得到了预期的结果:

    Map(function(x,y) abs(sweep(x,2,y,FUN="-"))/(sweep(abs(x),2,abs(y),FUN="+")),
        listA,
        listB)
    

    例如:

    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
    

    匹配长期计算:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      相关资源
      最近更新 更多