如何使用多个语句从if到ifelse进行向量化? [英] How to vectorize from if to ifelse with multiple statements?

查看:46
本文介绍了如何使用多个语句从if到ifelse进行向量化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚读到矢量化可以提高性能并显着减少计算时间,对于if()else来说,最佳选择是ifelse().

I just read that vectorization increases performance and lowers significantly computation time, and in the case of if() else , best choice is ifelse().

我的问题是我在for循环中有一些if语句,每个if语句包含多个赋值,如下所示:

My problem is I got some if statements inside a for loop, and each if statement contains multiple assignments, like the following:

x <- matrix(1:10,10,3)

criteria <- matrix(c(1,1,1,0,1,0,0,1,0,0,
                     1,1,1,1,1,0,0,1,1,0,
                     1,1,1,1,1,1,1,1,1,1),10,3) #criteria for the ifs
output1 <- rep(list(NA),10) #storage list for output
for (i in 1:10) {
  if (criteria[i,1]>=1) {
    output1[[i]] <- colMeans(x)
    output1[[i]] <- output1[[i]][1] #part of the somefunction output
  } else { 
    if(criteria[i,2]>=1) {
      output1[[i]] <- colSums(x)
      output1[[i]] <- output1[[i]][1] #the same
    } else {
      output1[[i]] <- colSums(x+1)
      output1[[i]] <- output1[[i]][1] #the same
    }}}

如何将其翻译为ifelse?

How can I translate this into ifelse?

提前谢谢!

推荐答案

请注意,您不需要for循环,因为使用的所有操作都是矢量化的:

Note that you don't need a for loop as all operations used are vectorized:

output2 <- ifelse(criteria[, 1] >= 1, 
             colMeans(x)[1], 
             ifelse(criteria[, 2] >= 1, 
               colSums(x)[1], 
               colSums(x+1)[1]))

identical(output1, as.list(output2))
## [1] TRUE

这篇关于如何使用多个语句从if到ifelse进行向量化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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