本文介绍了在R中度过十年的十年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一组日期定为最近的十年,例如:

I would like to floor a set of dates to the nearest decade, e.g:

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

我希望可以在Lubridate中做到这一点,例如:

I was hoping I could do this in Lubridate, as in:

floor_date(1922, 'decade')

但是我得到:

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

有没有办法优雅地做到这一点,也许避免一堆if-else语句进行装箱,并希望避免一堆cut进行分组?

Is there any way to do this gracefully, perhaps avoiding a bunch of if-else statement to do the binning, and hopefully avoiding a bunch of cuts to do the grouping?

推荐答案

R底一年中最接近的十年:

将模量视为提取最右边数字并用其减去原始年份的一种方法. 1998-8 = 1990

Think of Modulus as a way to extract the rightmost digit and use it to subtract from the original year. 1998 - 8 = 1990

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

R中的最高年份到最近的十年:

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

Ceiling is exactly like floor, but add 10.

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

R中的整整一年到最近的十年:

整数除法会将您的1998年转换为199.8,四舍五入为整数200,再乘以10即可返回2000.

Integer division converts your 1998 to 199.8, rounded to integer is 200, multiply that by 10 to get back to 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

Another way to round to nearest decade:Neat trick with Rscript core function round such that the second argument digits can take a negative number. See: https://www.rdocumentation.org/packages/base/versions/3.6.1/topics/Round

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

不要用这个小东西在管道胶带上害羞,这是将设备固定在一起的唯一方法.

Don't be shy on the duct tape with this dob, it's the only thing holding the unit together.

这篇关于在R中度过十年的十年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 04:43