首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R中向量化函数内部的运算

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

Stack Overflow用户
提问于 2019-12-03 03:36:46
回答 1查看 45关注 0票数 3

我有一个虚构的非向量函数,它接受两个参数作为输入。我有一个类似的(不完全相同的)向量函数,它对参数列表起作用。

但是,在非向量函数中,我还可以对参数本身进行一些操作(请参阅带注释的行)。我正在尝试找出一种方法,在函数的向量形式中也能做到这一点。

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
> 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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-03 03:45:08

由于i只接受单个值,因此它既可以与if/else一起使用,也可以与switch一起使用

代码语言:javascript
复制
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进行比较

代码语言:javascript
复制
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

代码语言:javascript
复制
Vectorize(nonvectorfunction)(sample.list, i = 1)
#[1] 2.162278 2.000000 1.828427 2.162278
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59145579

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档