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.
Following Adam K idea, but with a bit more of optimized regex (and making use of vectorisation, which is good idea in R):
fit2<-lm(CO~NO2,data=df)
test <- stargazer(fit2,type="text",)
It is a two line regex: you need to find the number (here of more than five numbers), that are string with number, comma and points
m <- gregexpr("([0-9\\.,]{5,})", test)
you need to apply a transformation function to that (here supress the comma, make a number, and display it in scientific with 2 digits. You can consider also the formatC
which gives a lot of possibility):
f = function(x){
sprintf("%.2e",as.numeric( gsub(",","",x)))
}
and you apply it to your regex using the regmatches
function
regmatches(test, m) <- lapply(regmatches(test, m), f)
test
[1] ""
[2] "========================================================"
[3] " Dependent variable: "
[4] " ------------------------------------"
[5] " CO "
[6] "--------------------------------------------------------"
[7] "NO2 6.26e+02** "
[8] " (2.41e+02) "
[9] " "
[10] "Constant 1.81e+18*** "
[11] " (4.62e+17) "
[12] " "
[13] "--------------------------------------------------------"
[14] "Observations 10 "
[15] "R2 4.58e-01 "
[16] "Adjusted R2 3.90e-01 "
[17] "Residual Std. Error 1.57e+17 (df = 8)"
[18] "F Statistic 6.76e+00** (df = 1; 8) "
[19] "========================================================"
[20] "Note: *p<0.1; **p<0.05; ***p<0.01"
To otbain the same output as the original:
print(as.data.frame(test),quote = F,row.names = FALSE)
test
========================================================
Dependent variable:
------------------------------------
CO
--------------------------------------------------------
NO2 6.26e+02**
(2.41e+02)
Constant 1.81e+18***
(4.62e+17)
--------------------------------------------------------
Observations 10
R2 4.58e-01
Adjusted R2 3.90e-01
Residual Std. Error 1.57e+17 (df = 8)
F Statistic 6.76e+00** (df = 1; 8)
========================================================
Note: *p<0.1; **p<0.05; ***p<0.01
the data:
df <- read.table(text = "
CO NO2 SM
2.750000e+18 1.985136e+15 0.2187433
2.980000e+18 2.144211e+15 0.1855678
2.810000e+18 1.586491e+15 0.1764805
3.010000e+18 1.755409e+15 0.2307153
3.370000e+18 2.205888e+15 0.2046671
3.140000e+18 2.084682e+15 0.1834232
2.940000e+18 1.824735e+15 0.1837391
3.200000e+18 2.075785e+15 0.1350665
3.060000e+18 1.786481e+15 0.1179924
2.750000e+18 1.645800e+15 0.2037340",header = T)