Created
November 11, 2023 21:30
-
-
Save joAschauer/8dfd50dd1c99e6931c9266381cb45597 to your computer and use it in GitHub Desktop.
rounding columns in R dataframe based on condition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(dplyr) | |
df <- structure( | |
list( | |
column1 = c(0.001234, | |
0.564324, | |
1.234342, | |
0.007839, | |
0.837483, | |
2.493993), | |
column2 = c(0.123493, | |
0.005643, | |
1.234342, | |
0.7839, | |
0.008374, | |
2.493993), | |
column3 = c(0.001234, | |
0.564324, | |
1.234342, | |
0.007839, | |
0.837483, | |
2.493993), | |
column4 = c(0.001234, | |
0.564324, | |
1.234342, | |
0.007839, | |
0.837483, | |
2.493993) | |
), | |
row.names = c(NA, -6L), | |
class = c("tbl_df", | |
"tbl", "data.frame") | |
) | |
df_rounded <- mutate_at( | |
df, | |
.vars = vars(column1, column2, column3, column4), | |
.funs = ~ case_when( | |
abs(.x) >= 1 ~ round(.x, digits = 0), | |
0.1 <= abs(.x) & abs(.x) < 1 ~ round(.x, digits = 1), | |
abs(.x) < 0.1 ~ round(.x, digits = 2), | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment