I just ran a statisitical model and i want it to display the results of the model as a table using stargazer. However, the large numbers are displayed in full.
To do this, you can write your own function to take the large numbers and put them into scientific notation.
stargazer
package:library(stargazer)
set.seed(1)
C <- data.frame("A" = rnorm(10000, 30000, 10000),
"B" = rnorm(10000, 7500, 2500))
stargazer
results table in an object:fit2 <- lm(A ~ B, data = C)
myResults <- stargazer(fit2, type = "text")
stargazer
table and convert large numbers into scientific notation. (This is not very flexible but can be with simple modifications. Right now only works for 1,000 - 99,999)fixNumbers <- function(stargazer.object){
so <- stargazer.object
rows <- grep(".*[\\d+],[\\d+].*", so, perl = T)
for(row in rows){
# Get number and format into scientific notation
number <- as.numeric(sub(".*([0-9]{1,2}),([0-9]+\\.?[0-9]*).*", "\\1\\2", so[row], perl = T))
formatted_num <- sprintf("%.2e", number)
so[row] <- sub("(.*)[0-9]{1,2},[0-9]+\\.?[0-9]*(.*)", paste0("\\1", formatted_num, "\\2"), so[row], perl = T)
}
# Print result
for(i in 1:length(so)){
cat(so[i], "\n")
}
}
fixNumbers
) your stargazer
object:fixNumbers(myResults)
-- Here's all the code in one chunk: --
library(stargazer)
set.seed(1)
C <- data.frame("A" = rnorm(10000, 30000, 10000),
"B" = rnorm(10000, 7500, 2500))
fit2 <- lm(A ~ B, data = C)
myResults <- stargazer(fit2, type = "text")
fixNumbers <- function(stargazer.object){
so <- stargazer.object
rows <- grep(".*[\\d+],[\\d+].*", so, perl = T)
for(row in rows){
# Get number and format into scientific notation
number <- as.numeric(sub(".*([0-9]{1,2}),([0-9]+\\.?[0-9]*).*", "\\1\\2", so[row], perl = T))
formatted_num <- sprintf("%.2e", number)
so[row] <- sub("(.*)[0-9]{1,2},[0-9]+\\.?[0-9]*(.*)", paste0("\\1", formatted_num, "\\2"), so[row], perl = T)
}
# Print result
for(i in 1:length(so)){
cat(so[i], "\n")
}
}
fixNumbers(myResults)