是否可以将数据帧中的数字四舍五入到最接近的整数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)
我试过这种方式,但它不工作的data.frame
使用round
与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
如果你想四舍五入到20,也许像这样?
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
您可以使用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
您也可以将舍入更改为不同的倍数(例如,到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
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