I have the following dataframe in R. I'm trying to create a table using kableExtra
, is there a way to print the zero decimal point for the integers in the table (so that the 7's in my dataframe are printed as 7.0 instead)? I would just like all of the numbers in my table to have consistent decimal points when I print my table
data <- structure(list(Model = c("ARIMA", "Actual", "Forecast", "Error",
"STIF", "Actual", "Forecast", "Error", "Adjusted Forecast", "Actual",
"Forecast", "Error"), `*Dec 2022` = c(NA, 6.9, 6.8, 0.1, NA,
6.9, 6.6, 0.3, NA, 6.9, 6.7, 0.2), `*Jan 2023` = c(NA, 7, 6.8,
0.2, NA, 7, 6.8, 0.2, NA, 7, 6.9, 0.1), `*Feb 2023` = c(NA, 7.2,
6.2, 1, NA, 7.2, 6.9, 0.3, NA, 7.2, 6.6, 0.6), Average = c(NA,
7, 6.6, 0.4, NA, 7, 6.8, 0.3, NA, 7, 6.7, 0.3)), row.names = c(NA,
-12L), class = c("tbl_df", "tbl", "data.frame"))
library(kableExtra)
library(tidyverse)
data %>%
mutate_if(is.numeric, ~as.character(.)) %>%
replace(is.na(.), " ") %>%
kable(caption="Short-Term Forecast Errors \\label{Table6}", booktabs = T, escape = FALSE, align = 'lcccc') %>%
kable_styling(latex_options = c("HOLD_position"), font_size = 9)
To display the same number of decimal points in the table, you can use the format()
function. Your code may look like this :
data %>%
mutate_if(is.numeric, ~ifelse(is.na(.), " ", format(round(., 1)))) %>%
kable(caption="Short-Term Forecast Errors \\label{Table6}", booktabs = T, escape = FALSE, align = 'lcccc') %>%
kable_styling(latex_options = c("HOLD_position"), font_size = 9)
The round()
function is used to round the numeric values to one decimal places before formatting.