Home > Net >  Is it possible to round the numbers in a dataframe to the nearest integer 10?
Is it possible to round the numbers in a dataframe to the nearest integer 10?

Time:11-09

Is it possible to round the numbers in a data frame to the nearest integer 10?

df <- data.frame(a = c(17,1,15,5,1,1,11,0,24,0),
                 b = c(0,10,19,1,1,32,0,5,7,8),
                 c = c(1,1,12,18,7,3,12,1,1,20))


round_df <- function(x, digits) {
numeric_columns <- sapply(x, mode) == 'numeric'
x[numeric_columns] <-  round_any(x[numeric_columns], digits)
x
}
df_10 <- round_df(df, 10)

I tried this way but it doesn't work for data.frame

CodePudding user response:

Use round with digits = -1:

round(df, digits = -1)

    a  b  c
1  20  0  0
2   0 10  0
3  20 20 10
4   0  0 20
5   0  0 10
6   0 30  0
7  10  0 10
8   0  0  0
9  20 10  0
10  0 10 20

If you want to round to 20, maybe something like this?

round(df / 20) * 20

    a  b  c
1  20  0  0
2   0  0  0
3  20 20 20
4   0  0 20
5   0  0  0
6   0 40  0
7  20  0 20
8   0  0  0
9  20  0  0
10  0  0 20

CodePudding user response:

You can use DescTools::RoundTo:

DescTools::RoundTo(df, multiple = 10, FUN = round)

    a  b  c
1  20  0  0
2   0 10  0
3  20 20 10
4   0  0 20
5   0  0 10
6   0 30  0
7  10  0 10
8   0  0  0
9  20 10  0
10  0 10 20

You can also change to round to different multiples (e.g., to 20).

DescTools::RoundTo(df, multiple = 20, FUN = round)

    a  b  c
1  20  0  0
2   0  0  0
3  20 20 20
4   0  0 20
5   0  0  0
6   0 40  0
7  20  0 20
8   0  0  0
9  20  0  0
10  0  0 20

CodePudding user response:

df[] <- lapply(df, plyr::round_any, accuracy = 10)

-ouptut

> df
    a  b  c
1  20  0  0
2   0 10  0
3  20 20 10
4   0  0 20
5   0  0 10
6   0 30  0
7  10  0 10
8   0  0  0
9  20 10  0
10  0 10 20
  • Related