【问题标题】:operations inside vectorised functions in RR中向量化函数内部的操作
【发布时间】:2019-12-02 19:36:46
【问题描述】:

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

但是在非向量函数中,我也可以对参数本身进行一些操作(请参阅带有 cmets 的行)。我也在想办法在函数的向量形式中做同样的事情。

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

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

【问题讨论】:

    标签: r


    【解决方案1】:

    由于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
    

    【讨论】:

    • 道歉我认为我已经让虚拟函数比它应该的更复杂了。我的目标是了解如何在编写一个可以处理向量列表的函数时对参数本身启用一些操作。
    • @itthrill 无需道歉。只是想了解原因。我更新了代码。请检查这是否有意义
    • 感谢 akrun,我喜欢 sapply 的想法。与其通过尝试向量化来使函数复杂化,不如将非向量化函数与 sapply 一起使用。
    • @itthrill 另一种选择是Vectorize你的非向量函数,更新了代码
    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多