简体   繁体   English

如何在R中编写具有多个条件的有效函数

[英]How to write an efficient function with multiple conditions in R

I am writing an R function to carry out this operation 我正在编写一个R函数来执行此操作 在此处输入图片说明

I am particularly wondering the best way to deal with the 2nd condition. 我特别想知道处理第二种情况的最佳方法。
I am currently using if statements within a function; 我目前在函数中使用if语句; the 2nd condition is dealt with using a nested if statement. 使用嵌套的if语句处理第二个条件。 I am curious if this is the best (fastest, most elegant) way to deal with this type of mathematical functions. 我很好奇这是否是处理此类数学函数的最佳方式(最快,最优雅)。

#Parameters
K.bc <- 10;K.bk<-100
W2.fg <- W2.fp <- 1000


#Function
F.2.sink <- function(K.bc, K.bk, W2.fg,W2.fp){ 
  if(W2.fg + W2.fg < K.bc) 
  {return(0)}

  if(K.bc < (W2.fg + W2.fg)) 
    if( W2.fg + W2.fg < (K.bc+K.bk))
       {return(W2.fg + W2.fp - K.bc)}

  if(W2.fg + W2.fp >= (K.bc+K.bk))
  {return(K.bk)}
}

F.2.sink(K.bc,K.bk,W2.fg,W2.fp)

看看: R中的Case语句等效 memisc包中有此函数cases 。不确定是否memisc ,但至少更具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM