R中向量化函数内部的运算

刺激

我有一个虚拟的非向量函数,该函数将两个参数作为输入。我有一个类似的(不完全相同)向量函数,可用于参数列表。

但是,在非矢量函数中,我也可以对参数本身进行一些操作(请参考带有注释的行)。我正在尝试找出一种以向量的向量形式进行相同操作的方法。

nonvectorfunction<-function(x,i){

  if (i==1){
    x<-x^0.5 # not implemented in vectorfunction
    if (x==10){
      x<-x+1
    } else {
      x<-x-1
    }
  }

  if (i==2){

    x<-x^(1/3) # not implemented in vectorfunction
    if (x==10){
      x<-x-1
    } else {
      x<-x+1
    }
  }
  return(x)
}


vectorfunction <- function(x,i) {

  x <- case_when(
    i==1 ~ case_when(
      x==10 ~ x+1,
      TRUE ~ x-1),
    i==2 ~ case_when (
      x==10 ~ x-1,
      TRUE ~ x+1
    ))

  return(x)
}



sample.list<-c(10,9,8,10)

nonvectorfunction(sample.list[1],1)
nonvectorfunction(sample.list[3],2)
nonvectorfunction(sample.list,1)


vectorfunction(sample.list,1)

输出:

> nonvectorfunction(sample.list[1],1)
[1] 2.162278
> nonvectorfunction(sample.list[3],2)
[1] 3
> nonvectorfunction(sample.list,1)
[1] 2.162278 2.000000 1.828427 2.162278
Warning message:
In if (x == 10) { :
  the condition has length > 1 and only the first element will be used
#this is expected because I am passing a list to non vector function
> 
> vectorfunction(sample.list,1)
[1] 11  8  7 11

如上所示,矢量化函数可以很好地处理列表。

阿克伦

由于i仅使用一个值,因此可以与if/else或一起使用switch

vectorfunction <- function(x,i) {
   switch(i, 
   `1` = {
        x <- x^0.5
        case_when(x == 10 ~ x + 1, TRUE ~ x - 1)
   },
   `2` = {
        x <- x^(1/3)
      case_when( x== 10 ~ x -1, TRUE ~ x +1)


   },
   default = x


   )


  }

vectorfunction(sample.list,1)
#[1] 2.162278 2.000000 1.828427 2.162278
vectorfunction(sample.list,2)
#[1] 3.154435 3.080084 3.000000 3.154435

与...比较 nonvectorfunction

sapply(sample.list, nonvectorfunction, i = 1)
#[1] 2.162278 2.000000 1.828427 2.162278
sapply(sample.list, nonvectorfunction, i = 2)
#[1] 3.154435 3.080084 3.000000 3.154435

或者nonvectorfunction可以Vectorized

Vectorize(nonvectorfunction)(sample.list, i = 1)
#[1] 2.162278 2.000000 1.828427 2.162278

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章