Search code examples
r

How to change the number of decimal places of the mean in a data frame


I can't change the number of decimal places in the mean. Below are my codes.

options(scipen=999)
df <- data.frame(rbind(Count, Min, Max, Mean, Median, Percmissing, PercZero, Percone, Percnegative))
    rownames(df) = c("Number of policies", "Min", "Max", "Mean", "Median", "% Missing", "% Zero", "% One", "% Negative") 
    colnames(df)= c("Value")
    df[c(6:9),]<-as.character(percent(df[c(6:9),]))

And this is the output

> df
                              Value
Number of policies            13904
Min                         -249000
Max                       550000000
Mean               49579186.6175847
Median                     22000000
% Missing                    45.68%
% Zero                        0.46%
% One                         3.61%
% Negative                    0.01%

As you can see the mean has a lot of decimal places and I want it to be just 2 decimal places. I tried the following code but it does not work.

Mean <- mean(dataV, na.rm=TRUE, is.numeric=TRUE)
round(Mean, digits=2)

And

options(digits=2)

Solution

  • The round function does not change the reference. You need to redefine the Mean variable:

    Mean = round(Mean,2)