问题
I have a dataframe values
as shown below
January February March
0.02345 0.03456 0.04567
0.05432 0.06543 0.07654
I need a command to round each of these values to 3 decimal points. Output should be as shown below
January February March
0.023 0.035 0.046
0.054 0.065 0.077
回答1:
In case your data frame contains non-numeric characters you may be willing to make use of the function by Jeromy Anglim:
round_df <- function(x, digits) {
# round all numeric variables
# x: data frame
# digits: number of digits to round
numeric_columns <- sapply(x, mode) == 'numeric'
x[numeric_columns] <- round(x[numeric_columns], digits)
x
}
round_df(data, 3)
I think it's neat and quick approach to handle the rounding problem across heterogeneous data frames.
回答2:
As indicated by @DavidArenburg, you can also use options
. This can be done either globally or via print
. I generally prefer the latter if it's just for rendering a single data.frame
where I don't want to actually lose the original (raw) data.
Example:
## Sample data frame
mydf <- data.frame(January = c(0.02345, 0.05432), February = c(0.03456, 0.06543),
March = c(0.04567, 0.07654), non_numeric = c("abcdefgh", "ijklmno"))
mydf
# January February March non_numeric
# 1 0.02345 0.03456 0.04567 abcdefgh
# 2 0.05432 0.06543 0.07654 ijklmno
Here, we use the digits
argument in print
:
print(mydf, digits = 2)
# January February March non_numeric
# 1 0.023 0.035 0.046 abcdefgh
# 2 0.054 0.065 0.077 ijklmno
This is the same as if we had used format
(which has a default method for data.frame
s. See ?format.data.frame
for more information on the options).
format(mydf, digits = 2)
Alternatively, as recommended by @David:
## Setting `options`:
options(digits = 2)
mydf
# January February March non_numeric
# 1 0.023 0.035 0.046 abcdefgh
# 2 0.054 0.065 0.077 ijklmno
options(digits = 7) ## Reset default options
来源:https://stackoverflow.com/questions/29875914/rounding-values-in-a-dataframe-in-r