When I use the apply statement to run the function it outputs tables with a comma separating each one. I've tried multiple things to see if I can get the commas to stop appearing and keep failing.
Rewrote code to provide example for you...
---
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 )`
Needs to stay in R, using markdown, outputting in either PDF or Word. I used apply statements but willing to use whatever works.
Seems painfully simple and I feel silly asking. Appreciate any help - also identify that this function can be recreated using far less code...I'm not asking for that, just how to get rid of the commas in between each run (or, in this case, number).
Thanks much
Normally your inline R code should return a scalar (an object of length 1). In your case, sapply(2:4, ...)
will return an object of length 3. By default, knitr will concatenate all elements separated by commas. If that is not desired, you can concatenate them by yourself to make a scalar, e.g.,
`r paste(sapply(2:4, tabs), collapse = '\n\n')`