对特定数字值的舍入数字

时间:2018-02-22 08:37:01

标签: r rounding

我希望将某个十进制日期舍入到今年或下一年,具体取决于小数是小于还是大于xxxx.75(十月)。它用于将历史食品价格添加到时间序列中。

table(Marriages$stop)

1721.09863013699 1728.53825136612 1728.66120218579 1730.13698630137  1730.3698630137  1730.6301369863 1732.15573770492 
               2                2                2                2                2                2                2 
1732.56830601093 1733.10410958904 1736.40163934426 1736.63114754098  1736.7650273224 1740.10109289617 1740.41530054645 
               2                2                2                2                2                2                2 
1741.54794520548  1742.2904109589 1742.66849315068 1742.74520547945 1742.82191780822 1743.14520547945 1743.81643835616 
               2                2                2                2                2                2                2 

这是我到目前为止尝试的方式:

Marriages$year <- ifelse(Marriages$tstop...), round(Marriages$tstop - 1, digits = 0), round(Marriages$tstop, digits = 0))

我在if子句的第一部分中遗漏了一条声明。我怎样才能找到我的停止年份的第一和第二位并相应地围绕它?

2 个答案:

答案 0 :(得分:0)

试试这个:

您的数据

  test<-c(1721.09863013699,1728.53825136612,1736.765027322)

您的输出

  to_round_up<-test-trunc(test,0)>0.75
  test[to_round_up]<-test[to_round_up]+1
  trunc(test,0)
[1] 1721 1728 1737

答案 1 :(得分:0)

您可以通过简单地从自身中减去内部数字来获取小数,检查它是否大于0.75并相应地向上或向下舍入。

对于矢量:

x <- c(1721.09863013699, 1728.53825136612, 1728.66120218579,
       1730.13698630137,  1730.3698630137,  1730.6301369863,
       1732.15573770492, 1732.56830601093, 1733.10410958904,
       1736.40163934426, 1736.63114754098, 1736.7650273224,
       1740.10109289617, 1740.41530054645, 1741.54794520548,
       1742.2904109589, 1742.66849315068, 1742.74520547945,
       1742.82191780822, 1743.14520547945, 1743.81643835616)


ifelse(x - floor(x) >= 0.75, ceiling(x), floor(x))

返回:

[1] 1721 1728 1728 1730 1730 1730 1732 1732 1733 1736 1736 1737 1740
[14] 1740 1741 1742 1742 1742 1743 1743 1744