问题
I was using stargazer today to make some basic summary tables, and noticed some strange behavior:
library(stargazer)
my_df <- data.frame(speed = c(3.00,3.20,3.00,3.20,3.10,2.90),
age = c(22,24,24,28,19,25))
stargazer(my_df, type="text",
summary.stat = c("min", "mean", "max"),
digits = 2)
Output is:
=======================
Statistic Min Mean Max
-----------------------
speed 3 3.07 3
age 19 23.67 28
-----------------------
Clearly min
should be 2.90 and max
should be 3.20, as I've specified digits=2
...am I losing my marbles? I'm using stargazer 5.2.2 and R 3.6.3 if it matters.
回答1:
That looks suspiciously like an undocumented behaviour (aka bug).
I may be wrong, but it seems that the function is inspecting the first value of each variable to determine how to present the min/max results, ignoring the digits
argument if it finds anything that looks like an integer. For example, change the first value from 3.00 to 3.10 and you get the expected output.
my_df <- data.frame(speed = c(3.10,3.20,3.00,3.20,3.10,2.90),
age = c(22,24,24,28,19,25))
stargazer(my_df, type="text",
summary.stat = c("min", "mean", "max"),
digits = 2)
=========================
Statistic Min Mean Max
-------------------------
speed 2.90 3.08 3.20
age 19 23.67 28
-------------------------
I tried this with the mtcars dataset and got the same behaviour.
stargazer(mtcars[,c("mpg","drat","wt","qsec")], type='text', digits=2)
=========================================================
Statistic N Mean St. Dev. Min Pctl(25) Pctl(75) Max
---------------------------------------------------------
mpg 32 20.09 6.03 10 15.4 22.8 34
drat 32 3.60 0.53 2.76 3.08 3.92 4.93
wt 32 3.22 0.98 1.51 2.58 3.61 5.42
qsec 32 17.85 1.79 14.50 16.89 18.90 22.90
---------------------------------------------------------
head(mtcars[,c("hp","mpg","drat","wt","qsec")])
# hp mpg drat wt qsec
# Mazda RX4 110 21.0 3.90 2.620 16.46
# Mazda RX4 Wag 110 21.0 3.90 2.875 17.02
# Datsun 710 93 22.8 3.85 2.320 18.61
# Hornet 4 Drive 110 21.4 3.08 3.215 19.44
# Hornet Sportabout 175 18.7 3.15 3.440 17.02
# Valiant 105 18.1 2.76 3.460 20.22
So, I don't think you are losing your marbles. But you should report this to the package author and see what he (Marek Hlavac) says.
来源:https://stackoverflow.com/questions/61553731/r-why-does-stargazer-return-incorrect-values-for-min-and-max-with-this-datafram