2015-02-24 203 views
1

问题

我需要,其通过对于不同的范围(例如,我测量电流和仪表计算测量的不确定度的函数,如果它是在2毫安的不确定性的范围是测量值的0.1 % + 3 dig)。如果该函数能够获取矢量并返回矢量而不是数字,则更好。替代嵌套ifelse()中的R语句

我写了很多if的函数,但它返回警告the condition has length > 1 and only the first element will be used。经过一段时间的研究,我发现R中的if s被设计用于处理表达式,该表达式可以计算出单个布尔值,而ifelse可以处理向量。

但由于有大约10个链else if s同样的事情与ifelse s会相当丑陋。

if S:

S.I = function(I) { 
    if(I<=(2*10^(-6))){ 
     0.1*I/100 + 3*10^(-9) 
    } else if(I<=(20*10^(-6))) { 
     ... 
    } 
    ... 
} 

ifelse小号

S.I = function(I) { 
    ifelse(I<=(2*10^(-6)),0.1*I/100 + 3*10^(-9),ifelse(I<=(2*10^(-6)),...,ifelse(...))) 
} 

问题

有没有在这种情况下ifelse秒的方法吗?

+1

你能提供一个可重复的例子吗? – Khashaa 2015-02-24 15:48:40

+0

您不必在同一行上完成'ifelse'。 – James 2015-02-24 15:52:17

+0

尽管不能像当前编写的那样将向量投入到“SI”中,但如果更容易,可以继续使用if-else范例,然后使用可将向量传递给的向量化(SI)' – rawr 2015-02-24 15:53:37

回答

3

R中这样做的通常方法可能是cut;这里是一个例子。

## some sample current values 
I <- c(1e-6, 2e-6, 1e-5, 2e-5, 1e-4, 2e-4, 1e-3, 2e-3) 
## define the endpoints for the different ranges 
breaks <- c(-Inf, 2*10^(-6:3)) 
## for each range, define the percent of the original 
## and the amount to add 
percent <- c(0.10, 0.11, 0.12, 0.13) 
dig <- c(3e-9, 3e-8, 3e-7, 3e-6) 
## get the range that each value falls in 
range <- cut(I, breaks, labels=FALSE) 
## and multiply by the right percent and add the right extra amount 
I*percent[range]/100 + dig[range] 
1

正如您所指出的那样,您的函数仅适用于单个值,因为if不作用于矢量。解决方案是将每个向量的值逐个发送到函数。

[R提供了一组apply功能来做到这些(这就像一个循环,但速度更快):如果你想在矢量代码申请S.I几次

result = sapply(I_vector, S.I) 

,它可以是值得使用包装:

wrapper_S.I = function(I) { return(sapply(I_vector, S.I)) } 
result = wrapper_S.I(I_vector) 

注:您还可以Vectorize创建包装:

wrapper_S.I = Vectorize(S.I) 

它创建一个包含额外控件的包装。