有条件的劳累?

问题描述 投票:1回答:1

我试着做一个与lapply for循环一起工作的函数。我对R来说很新,而且不能与lapply相提并论。我特别不知道如何制作“if”条件。

我当前使用for循环的代码看起来像那样(它规范了音量系列):

function(TableVolume,VolumeM,VolumeStD,n){
TableBN = TableVolume[n:nrow(TableVolume),]

for(k in 1:nrow(TableBN)){for (i in 2:ncol(TableBN)){if(!is.na(VolumeM[k,i]) && (VolumeM[k,i]) && (TableVolume[n-1+k,i]>VolumeM[k,i]+1.96/sqrt(n)*VolumeStD[k,i])){TableBN[k,i]=TableVolume[n-1+k,i]/VolumeM[k,i]}else{TableBN[k,i]=0}}}
TableBN=TableBN[n:nrow(TableVolume),]
return(TableBN)
}

我从Apply over two data frames知道如何使用2数据帧的功能,但我仍然没有看到如何处理测试。

谢谢你的支持,文森特

r if-statement multiple-tables lapply
1个回答
0
投票

您需要使用lapply(或其他适用的家庭功能)。当你有一些非向量化函数应用于向量化参数时,通常需要它。您的函数和条件是算术函数的组合,它们很好地矢量化。所以你可以使用子集和ifelse函数,请看如下:

set.seed(123)

# simulation
TableBN <- matrix(1:12, nrow = 3)
VolumeM <- matrix(12:1, nrow = 3)
VolumeStD <- matrix(12:1, nrow = 3)
TableVolume <- matrix(abs(rnorm(10)), nrow = 5)


# function
f <- function(TableVolume, VolumeM, VolumeStD, n){
  TableBN <- TableVolume[n:nrow(TableVolume), ]

  ifelse(
    test = !is.na(VolumeM) && VolumeM && TableBN[, -1] > (VolumeM + 1.96 / sqrt(n) * VolumeStD), 
    yes = TableBN[, -1] / VolumeM,
    no = 0)
}

# Test
f(TableVolume, VolumeM, VolumeStD, 3)

输出:

0
© www.soinside.com 2019 - 2024. All rights reserved.