2015-12-22 170 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)不会得到逗号。