标准 R 输出看起来像这样
> 3
[1] 3
删除前缀 1您可以使用
> cat(3)
3
有没有办法全局删除它?还是要包
cat()
周围的一切?此外,我在 knitr 中使用它,所以如果没有 R 全局设置,可能有一个 knitr 宽设置,我确实看过,但看不到一个。
编辑:有人问为什么要这样,比如如果你想构建一个像下面这样的报告。
[1]
只是不需要,对没有 R 用户(也就是观众)没有任何意义。附加信息:在 knitr 中,您可以使用\Sexpr{} 或
r ...
评估某些内容,在这种情况下它不会打印 [1]
.例如,如果您有:There are `r sum(mtcars$cyl==6)` cars with 6 cylinders.
你会得到:
有7辆6缸的汽车。
作为您的输出,而不是:
有
[1]
7 辆 6 缸汽车。
最佳答案
没有什么是不可能的。看看可以用 knitr hooks 做什么.
玩得开心!
Rmarkdown script gist
# A Prefix nulling hook.
# Make sure to keep the default for normal processing.
default_output_hook <- knitr::knit_hooks$get("output")
# Output hooks handle normal R console output.
knitr::knit_hooks$set( output = function(x, options) {
comment <- knitr::opts_current$get("comment")
if( is.na(comment) ) comment <- ""
can_null <- grepl( paste0( comment, "\\s*\\[\\d?\\]" ),
x, perl = TRUE)
do_null <- isTRUE( knitr::opts_current$get("null_prefix") )
if( can_null && do_null ) {
# By default R print output aligns at the right brace.
align_index <- regexpr( "\\]", x )[1] - 1
# Two cases: start or newline
re <- paste0( "^.{", align_index, "}\\]")
rep <- comment
x <- gsub( re, rep, x )
re <- paste0( "\\\n.{", align_index, "}\\]")
rep <- paste0( "\n", comment )
x <- gsub( re, rep, x )
}
default_output_hook( x, options )
})
knitr::opts_template$set("kill_prefix"=list(comment=NA, null_prefix=TRUE))
普通的:
```{r}
print( 1:50 )
```
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
## [24] 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
## [47] 47 48 49 50
空前缀
```{r, null_prefix=TRUE}
print( 1:50 )
```
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
## 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
## 47 48 49 50
设置为默认值(并删除注释字符串):
```{r}
knitr::opts_chunk$set(opts.label="kill_prefix")
```
```{r}
print( 1:50 )
```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
47 48 49 50
确保我们没有使用 [:digit:] 模式杀死字符串。
```{r}
print( paste0( paste0("[", 1:50), "]" ),quote = FALSE)
```
[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14]
[15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25] [26] [27] [28]
[29] [30] [31] [32] [33] [34] [35] [36] [37] [38] [39] [40] [41] [42]
[43] [44] [45] [46] [47] [48] [49] [50]
关于r - 如何删除 knitr 输出中的前缀(索引指示器)[1]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22524822/