You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将R语言DataFrame中的数值四舍五入至最接近的10的整数?

解决DataFrame数值四舍五入到最接近10的问题

原代码无效的核心原因有两个:

  • round_any函数属于plyr包,未加载该包会直接报错
  • 直接对多列数据框子集调用round_any,该函数仅支持向量输入,无法处理多列数据

下面提供两种可行的解决方法:

方法一:基础R实现(无需额外包)

用round(x/10)*10的逻辑实现四舍五入到最接近的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, base) {
  # 筛选数值型列
  num_cols <- sapply(x, is.numeric)
  # 对每个数值列应用四舍五入逻辑
  x[num_cols] <- lapply(x[num_cols], function(col) round(col / base) * base)
  return(x)
}

# 应用函数,四舍五入到最接近的10
df_10 <- round_df(df, 10)
print(df_10)

运行后输出结果:

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

方法二:使用plyr包的round_any函数

如果一定要用round_any,需要先加载plyr包,并且用lapply逐个处理数据框的数值列:

# 加载plyr包
library(plyr)

# 初始化示例数据框
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, is.numeric)
  # 用lapply逐个列调用round_any
  x[numeric_columns] <- lapply(x[numeric_columns], round_any, digits = digits)
  return(x)
}

# 应用函数
df_10 <- round_df(df, 10)

内容的提问来源于stack exchange,提问作者nando_5g

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 23:25:35