round_numeric.RdRounds all numeric columns of a data frame to a specified number of digits. Non-numeric columns and attributes are preserved.
round_numeric(x, digits)A data frame with all numeric columns rounded to the specified number of digits.
If digits is a named vector, only the specified columns are rounded to the
corresponding number of digits. If the name ".default" is included in the
vector, all numeric columns not explicitly named will be rounded to that
number of digits.
If digits is a single integer, all numeric columns are rounded to that
number of digits.
If digits is NULL, the data frame is returned unchanged.
data <- data.frame(
col1 = c(1.234, 2.345, 3.456),
col2 = c(4.567, 5.678, 6.789),
col3 = c(2.537, 4.658, 4.739),
non_numeric_col = c("A", "B", "C")
)
## round all numeric variables to two digits
round_numeric(data, digits = 2)
#> col1 col2 col3 non_numeric_col
#> 1 1.23 4.57 2.54 A
#> 2 2.35 5.68 4.66 B
#> 3 3.46 6.79 4.74 C
## round col1 to one digit and col2 to two digits
round_numeric(data, digits = c(col1 = 1, col2 = 2))
#> col1 col2 col3 non_numeric_col
#> 1 1.2 4.57 2.537 A
#> 2 2.3 5.68 4.658 B
#> 3 3.5 6.79 4.739 C
## round col1 to one digit and all other numeric variables to two digits.
round_numeric(data, digits = c(col1 = 1, .default = 2))
#> col1 col2 col3 non_numeric_col
#> 1 1.2 4.57 2.54 A
#> 2 2.3 5.68 4.66 B
#> 3 3.5 6.79 4.74 C