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

将数据框指定列数值四舍五入至最接近的0.25倍数

解决方案:将数值四舍五入到最近的0.25倍数

首先,你的数据集如下:

sample1 <-
  structure(list(ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 
                 L = c(1.31, 1.62, 1.93, 2.24, 2.55, 2.86, 3.17, 3.48, 3.79, 4.10)), 
            class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L))

要将L列数值四舍五入到最近的0.00、0.25、0.5或0.75,可以利用0.25是1/4的整数倍这一特性,通过以下步骤实现:

  • 将L列的每个数值乘以4,把问题转化为四舍五入到整数
  • 对乘积结果进行四舍五入
  • 将四舍五入后的整数除以4,得到目标数值

具体R代码如下(可选择添加新列或直接替换原列):

方法1:添加新列L_rounded

sample1$L_rounded <- round(sample1$L * 4) / 4

方法2:直接替换原L列

sample1$L <- round(sample1$L * 4) / 4

执行代码后,处理后的数据集示例如下:

> sample1
# A tibble: 10 × 3
      ID     L L_rounded
   <dbl> <dbl>     <dbl>
 1     1  1.31      1.25
 2     2  1.62      1.5 
 3     3  1.93      2   
 4     4  2.24      2.25
 5     5  2.55      2.5 
 6     6  2.86      2.75
 7     7  3.17      3.25
 8     8  3.48      3.5 
 9     9  3.79      3.75
10    10  4.1       4   

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:27:07