2012-06-13 77 views
0

原諒我這個不美觀的代碼,但我試圖讓它首先工作。 (「當然,這只是暫時的,除非它能正常工作」-red green)不規則的格式化行爲

我試圖創建一個函數,它將格式化數組中的數字,我需要它們。它看起來像這樣。

frmt <- function(x, rates=FALSE, thou=FALSE) { 
    ifelse(x==0, "0", 
    ifelse(x < 0.01 & thou==TRUE, "<0.01", 
    ifelse(x < 0.1 & thou==FALSE, "<0.1", 
    ifelse(signif(x, 2) < 1 & thou==TRUE, formatC(round(x,3), format='f', digits=3), 
    ifelse(signif(x, 2) < 1, formatC(round(x,2), format='f', digits=2), 
    ifelse(signif(x, 2) < 10, formatC(round(x,2), format='f', digits=1), 
    ifelse(rates==FALSE, formatC(signif(x, 2), big.mark=" ", format='d'), 
    ifelse(signif(x, 3) < 100, formatC(signif(x, 2), big.mark=" ", format='d'), formatC(signif(x, 3), big.mark=" ", format='d'))))))))) 
} 

它爲這個偉大工程:

> frmt(1413.612) 
[1] "1 400" 

但不是這樣的:

> frmt(c(0.0001, 0.0213, 0.25413, 1.0123, 9.9123, 15.124, 112.05, 1413.612, NA)) 
[1] "<0.1" "<0.1" "0.25" "1.0" "9.9" "0" "0" "0" NA 
+0

我意識到ifelse ()可能不是解決這個問題的最好方法。如果你想花時間更好地上學,我絕對歡迎它!謝謝! – Tom

回答

0

這是我終於得到了代碼工作

frmt <- function(x, rates=FALSE, thou=FALSE) { 
    ifelse(x==0, "0", 
    ifelse(x < 0.01 & thou==TRUE, "<0.01", 
    ifelse(x < 0.1 & thou==FALSE, "<0.1", 
    ifelse(signif(x, 2) < 1 & thou==TRUE, formatC(round(x,3), format='f', digits=3), 
    ifelse(signif(x, 2) < 1, formatC(round(x,2), format='f', digits=2), 
    ifelse(signif(x, 2) < 10, formatC(round(x,2), format='f', digits=1), 
    ifelse(x > 1 & rates==FALSE, formatC(signif(x, 2), big.mark=" ", format='d'), 
    ifelse(signif(x, 3) < 100, formatC(signif(x, 2), big.mark=" ", format='d'), formatC(signif(x, 3), big.mark=" ", format='d'))))))))) 
}