【问题标题】:Remove comma following apply statement and function in R删除 R 中 apply 语句和函数后的逗号
【发布时间】:2023-02-04 00:55:58
【问题描述】:

当我使用 apply 语句运行函数时,它输出的表用逗号分隔。我已经尝试了多种方法来查看是否可以让逗号停止出现并继续失败。

重写代码以为您提供示例...

---
output: pdf_document
---

```{r setup, include=FALSE, warning=FALSE}
knitr::opts_chunk$set( echo = FALSE , warning = FALSE , message = FALSE , cache = FALSE )

# Load libraries 
library( data.table )
library( kableExtra )
library( knitr )
library( ggplot2 )

```

```{r stackexample}
# Recreate comma issue after sapply 

cols <- list( diamonds )
dfs <- list( diamonds )
jan <- data.table( diamonds ) 
cols_jan <- colnames( diamonds[ , c( 1:4 , 7 ) ])

tabs <- function( number , design , dts ){
          
          x <- y <- z <- NULL 
          dts <- jan
          vars <- cols_jan[number]
          
          out <- x <- y <- z <- NULL 
          x <- dts[ , .( counts = .N ) , by= vars ]
          x <- x[ order( x[ , 1 ] ) ,  ]
          x[ , `:=` ( Percent = ifelse( counts < 30 , NA , counts/nrow( dts ))) , ]
          row.names( x ) <- NULL 
          x[ , counts := ifelse( counts < 30 , NA , as.numeric( counts )) , ]
                
          z <- x 
          z[ , `:=` (
                  counts = scales::number( counts , accuracy = 1 , big.mark="," ) ,
                  Percent = scales::percent( Percent , accuracy = 0.1 ) 
          )]  
                   
          colnames( z ) <- c( ' ' , 'Counts' , 'Frequency' )
          out <- knitr::kable( z , format = 'latex', booktabs = TRUE )
          out
          
          }

```

`r sapply( 2:4 , tabs )`

需要留在 R 中,使用 markdown,以 PDF 或 Word 输出。我使用了 apply 语句,但愿意使用任何有效的方法。

看起来很简单,我觉得很傻。感谢任何帮助 - 还确定可以使用更少的代码重新创建此函数......我不是要求那个,只是如何摆脱每次运行之间的逗号(或者,在这种情况下,数字)。

非常感谢

【问题讨论】:

  • 所以你的问题是:如何写成 "45678" 而不是 "45,678" ,对吧?我相当怀疑 ?knitr::kable 会为您提供有关附加函数参数的信息,以定义各种显示参数。是的:见format.args

标签: r function r-markdown knitr sapply


【解决方案1】:

问题是这一行:

counts = scales::number( counts , accuracy = 1 , big.mark="," )

您正在获取您的计数值(这是一个数字)并对其应用缩放函数,该函数对其进行缩放和格式化以进行漂亮的打印。在那里,您指定大数字分隔符应该是逗号 (big.mark=",")。

只需更改那里的设置即可解决此问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多