2015-12-22 265 views
1

我一直在使用一個很好的SO solution添加在一段時間knitr報告逗號分隔爲數字,不過這個功能似乎有一個意想不到的後果之前,我從來沒有遇到過:它截斷帶括號的字符串。我不明白爲什麼這個函數會影響我的字符串,所以不能很好地使用類。這是一個簡單的例子。逗號分隔和字符串截斷

1)保持代碼原樣和逗號分隔工作(2,015),但字符串被截斷(30.2 (10)。

enter image description here

2)拆下鉤,你看到相反:沒有逗號分離(2015),但該字符串是確定(30.2 (10.2))。

enter image description here

\documentclass{article} 

\begin{document} 

<<knitr, include=FALSE>>= 
    library(knitr) 
    nocomma <- function(x){structure(x,class="nocomma")} 
    knit_hooks$set(inline = function(x) { 
     if(!inherits(x,"nocomma")) return(prettyNum(x, big.mark=",")) 
     if(inherits(x,"nocomma")) return(x) 
     return(x) # default 
    }) 
@ 

<<ex>>= 
x <- paste0("30.2 ", "(", "10.2", ")") 
x 
# [1] "30.2 (10.2)" 
y <- "2015" 
@ 

The `nocomma()` function does a nice job putting a comma in \Sexpr{y}, but \Sexpr{x} gets truncated. 

\end{document} 

我喜歡掛鉤的做法是需要000的分離所有內嵌琴絃逗號沒有我不必手動使用的功能在每一個實例來設置逗號整個文檔。這可能不是一個很好的解決方案,我向其他人開放。但對我來說是非常實用的解決方案......直到今天,也就是當它打破了我的文檔中別的東西:與(的字符串。

+0

這不是用來作爲'Sexpr {nocomma(x)}'的東西嗎? – A5C1D2H2I1M1N2O1R2T1

+0

我添加了由方法(1)和(2) –

+0

生成的pdf的兩個屏幕截圖,@AnandaMahto該函數在鉤子中設置,因此您不必使用內聯。 –

回答

2

它看起來並不像你所使用的功能如預期。如果你看看at the answer to the question you link to,它帶有兩個實用的功能:

comma <- function(x){structure(x,class="comma")} 
nocomma <- function(x){structure(x,class="nocomma")} 

和稍微不同的功能定義:

knit_hooks$set(inline = function(x) { 
     if(inherits(x,"comma")) return(prettyNum(x, big.mark=",")) 
     if(inherits(x,"nocomma")) return(x) 
     return(x) # default 
    }) 

隨着comma("2015")nocomma(paste0("30.2 ", "(", "10.2", ")"))預期的使用情況。

您的版本已被修改爲總是嘗試輸入逗號,除非明確使用nocomma()。你寫:

nocomma()功能做了很好的工作,把一個逗號\Sexpr{y},但\Sexpr{x}被截斷。

實際上,nocomma()函數在你的例子中什麼都不做,因爲你從不使用它。你可以用用它---顧名思義,以防止逗號 ---這樣的:

,(逗號)在\Sexpr{y}自動添加,但使用nocomma()沒有增加逗號:\Sexpr{nocomma(x)}

如果你正在尋找一個更加自動化的解決方案,一些不要求您指定nocomma()當你要修改,你可以嘗試讓功能猜好一點(如我在我的評論中建議):

knit_hooks$set(inline = function(x) { 
     if(is.na(as.numeric(x))) return(x) 
     if(!inherits(x,"nocomma")) return(prettyNum(x, big.mark=",")) 
     return(x) # default 
    }) 

這將嘗試強制輸入數值。如果它沒有得到一個NA,那麼它會嘗試在其中放一個逗號,否則它會保持不變。就個人而言,我寧願只修改數字和不能碰的字符:

knit_hooks$set(inline = function(x) { 
     if(!(is.numeric(x)) return(x) 
     if(!inherits(x,"nocomma")) return(prettyNum(x, big.mark=",")) 
     return(x) # default 
    }) 

這個版本將只嘗試修改直線上升數字,所以2015會得到一個逗號; "2015"nocomma(2015)不會得到逗號。