Rounds all numeric columns of a data frame to a specified number of digits. Non-numeric columns and attributes are preserved.

round_numeric(x, digits)

Arguments

x

A data frame.

digits

Integer. Number of digits to round to. Or a named vector with variable names and digits to round. The name ".default" sets the digits value for all numeric variables that are not named in the vector.

Value

A data frame with all numeric columns rounded to the specified number of digits.

See also

Examples

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