【问题标题】:lapply with condition?有条件地申请?
【发布时间】:2012-06-26 14:09:14
【问题描述】:

我尝试使用 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 个数据帧的函数,但我仍然不知道如何处理测试。

感谢您的支持, 文森特

【问题讨论】:

  • 发现:stat.ethz.ch/pipermail/r-help/2011-May/277193.html
  • 我正在处理:二值化=function(TableVolume,VolumeM,VolumeStD,n) {lapply(TableVolume,function(h){lapply(VolumeM,function(u){ lapply(VolumeStD,function( v,n){ f(h,u,v,n)=h/(u+1.96*v/sqrt(n)) }) }) }) } WorkingTable=binarisation(TableVolume,VolumeM,VolumeStD,n) remplissage =function(WorkingTable){lapply(WorkingTable,function(u){ function(u)=max(u-1,0) })} 我试图让其工作

标签: r if-statement multiple-tables lapply


【解决方案1】:

您需要使用lapply(或其他应用家庭功能)。当您有一些非向量化函数应用于向量化参数时,通常需要它。您的函数和条件是算术函数的组合,它们被很好地矢量化了。所以你可以使用 subsetting 和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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多