2017-01-31 39 views
1

獲得不等式表達式(字符)的上限和下限的正確方法是什麼?這裏是一個例子:將不等式表達式(字符)解析爲數字範圍

df = structure(list(expressions = c("x<1", "x>1", "x==1", "x<=1", 
"x>=1")), .Names = "expressions", class = "data.frame", row.names = c(NA, 
-5L)) 

我的輸入是df$expressions。我想獲得df$minimumdf$maximum像下面

expressions minimum maximum 
1   x<1  NA 0.99999 
2   x>1 1.00001  NA 
3  x==1 1.00000 1.00000 
4  x<=1  NA 1.00000 
5  x>=1 1.00000  NA 

當只有<,從數中減去1e-5。當只有>時,將1e-5添加到數字中。

+0

爲什麼不寫一個函數,不等式表達式作爲字符輸入和'x'作爲數字輸入?正如你所說,'gsub'和'if ... else'完成了這個訣竅。 – ottlngr

+0

你說過:「只有<時,從數字中減去1e-5。」 - 所以有一個數字。必須有一個數字減去1e-5 ... – ottlngr

+0

哦,對不起,現在我明白了。當然,「數字」是1。無論如何,一個簡單的函數應該做到這一點。 – ottlngr

回答

1
#FUNCTION 
foo = function(eq, delta = 1e-5){ 
    #Extract the numerical portion of the expression 
    n = as.numeric(gsub("\\D+", "", eq)) 

    #Create vector x 
    x = c(-Inf, n - delta, n, n + delta, Inf) 

    #Evaluate eq by plugging in x and subset values of x where TRUE 
    y = x[eval(expr = parse(text = eq))] 

    return(range(y)) 
} 

t(sapply(df$expressions, foo)) 
#  [,1] [,2] 
#x<1  -Inf 0.99999 
#x>1 1.00001  Inf 
#x==1 1.00000 1.00000 
#x<=1 -Inf 1.00000 
#x>=1 1.00000  Inf 
1

完全不同的方法可能不符合您的要求。 但我想如果最終的目標是在實際數據上使用範圍,您實際上也可以選擇這種方法。

如果不是,這是值得嘗試:

library(dplyr) 

expressions = c('x < 1','x > 1','x == 1','x <= 1','x >= 1') 

df <- data.frame(x = seq(0,2,by=1e-05)) 

df %>% mutate_(.dots=setNames(expressions, seq_along(expressions))) %>% 
    gather(key,value, -x) %>% mutate(u = ifelse(value,x,NA)) %>% 
    group_by(key) %>% summarise(minimum = min(u, na.rm=T), maximum = max(u, na.rm=T)) %>% 
    mutate(key = factor(key, labels=expressions)) 

結果:

# A tibble: 5 × 3 
    key minimum maximum 
    <fctr> <dbl> <dbl> 
1 x < 1 0.00000 0.99999 
2 x > 1 1.00001 2.00000 
3 x == 1 1.00000 1.00000 
4 x <= 1 0.00000 1.00000 
5 x >= 1 1.00000 2.00000