R 中的一年到十年

Floor a year to the decade in R

我想将一组日期精确到最近的十年,例如:

1922 --> 1920,  
2099 --> 2090,  

我希望我能在 Lubridate 中做到这一点,如:

floor_date(1922, 'decade')

但我得到:

Error in match.arg(unit) : 
  'arg' should be one of “second”, “minute”, “hour”, “day”, “week”, “month”, “year”

有什么办法可以优雅地做到这一点,也许可以避免一堆 if-else 语句来进行分箱,并希望避免一堆 cuts 来进行分组?

你可以在这里使用一些整数除法。看看每个数字有多少个十年。

(c(1922, 2099) %/% 10) * 10
# [1] 1920 2090

您不能对整数使用 floor_date();它用于日期或日期时间对象。正如 MrFlick 的回答中已经建议的那样,您不需要 lubridate 来进行整数计算。如果你确实想使用 lubridate,可以这样做:


library(lubridate)

y <- ymd(c("2016-01-01", "2009-12-31"))
floor_date(y, years(10))
#> [1] "2010-01-01" "2000-01-01"

将 R 中的一年计算到最近的十年:

将模数视为提取最右边数字并使用它从原始年份中减去的一种方式。 1998 - 8 = 1990

> 1992 - 1992 %% 10 
[1] 1990
> 1998 - 1998 %% 10
[1] 1990

将 R 中的一年上限为最近的十年:

天花板与地板完全一样,但加 10。

> 1998 - (1998 %% 10) + 10
[1] 2000
> 1992 - (1992 %% 10) + 10
[1] 2000

将 R 中的一年舍入到最近的十年:

整数除法将你的 1998 转换为 199.8,四舍五入为整数 200,乘以 10 得到 2000。

> round(1992 / 10) * 10
[1] 1990
> round(1998 / 10) * 10
[1] 2000

方便花花公子复制面食给那些不喜欢思考的人:

floor_decade    = function(value){ return(value - value %% 10) }
ceiling_decade  = function(value){ return(floor_decade(value)+10) }
round_to_decade = function(value){ return(round(value / 10) * 10) }
print(floor_decade(1992))
print(floor_decade(1998))
print(ceiling_decade(1992))
print(ceiling_decade(1998))
print(round_to_decade(1992))
print(round_to_decade(1998))

打印:

# 1990
# 1990
# 2000
# 2000
# 1990
# 2000

来源: https://rextester.com/AZL32693

另一种四舍五入到最近十年的方法: Rscript 核心函数 round 的巧妙技巧,使第二个参数数字可以取负数。参见:https://www.rdocumentation.org/packages/base/versions/3.6.1/topics/Round

round(1992, -1)    #prints 1990
round(1998, -1)    #prints 2000

不要对这个 Dob 的管道胶带感到害羞,它是唯一将装置固定在一起的东西。

你也可以这样使用floor函数:

floor(1922 / 10) * 10
# [1] 1920

如果你需要四舍五入而不是地板:

round(1922, digits = -1)
# [1] 1920