Rounding off a value in an inline R code

Hello everyone and Happy Monday.

May I ask how can I round off or set the number of decimal places of x in an inline R code if x is extracted from a table?
My inline code are as follows:

“There has been r as.character(wk42[18,3]) COVID-19 admissions per 100,000 population in the Philippines.”

Result:
“There has been 0.100000001490116 COVID-19 admissions per 100,000 population in the Philippines.”

I would like to set it to just one decimal place (0.1 C19 ad per 100k pop’n).
I have tried the following and all resulted to an error:

r round(as.character(wk42[18,3]), 1)
r as.character(wk42[18,3]), round( , 1)
r sprintf("%.1f", as.character(wk42[18,3])

Thank you.

1 Like

Hello,

You have a few options here, you could use the round function to round wk42 as a numeric or the print function to trim the digits as a character.

See below:

x <- 1.234567

# round
round(x, digits = 1)
#> [1] 1.2

# print
print(x, digits = 2)
#> [1] 1.2

Created on 2023-10-30 with reprex v2.0.2

Session info
sessionInfo()
#> R version 4.3.1 (2023-06-16)
#> Platform: x86_64-apple-darwin20 (64-bit)
#> Running under: macOS Ventura 13.5.2
#> 
#> Matrix products: default
#> BLAS:   /Library/Frameworks/R.framework/Versions/4.3-x86_64/Resources/lib/libRblas.0.dylib 
#> LAPACK: /Library/Frameworks/R.framework/Versions/4.3-x86_64/Resources/lib/libRlapack.dylib;  LAPACK version 3.11.0
#> 
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#> 
#> time zone: America/Toronto
#> tzcode source: internal
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> loaded via a namespace (and not attached):
#>  [1] styler_1.10.2     digest_0.6.33     fastmap_1.1.1     xfun_0.40        
#>  [5] magrittr_2.0.3    glue_1.6.2        R.utils_2.12.2    knitr_1.44       
#>  [9] htmltools_0.5.6.1 rmarkdown_2.25    lifecycle_1.0.3   cli_3.6.1        
#> [13] R.methodsS3_1.8.2 vctrs_0.6.4       reprex_2.0.2      withr_2.5.1      
#> [17] compiler_4.3.1    R.oo_1.25.0       R.cache_0.16.0    purrr_1.0.2      
#> [21] rstudioapi_0.15.0 tools_4.3.1       evaluate_0.22     yaml_2.3.7       
#> [25] rlang_1.1.1       fs_1.6.3

All the best,

Tim

Hi,
This is what I did and it worked:

x ← (wk42[18,3])
x1 ← round(x, digits = 1)

There has been r x1 COVID-19 admissions per 100,000 population in the Philippines.

Thank you so much.

Regards,
Echo

1 Like

Hello,

I am glad to hear that things worked out - can you please mark this as solved?

All the best,

Tim