如何将日期季度分配给整数值
我有一个数据集,其中包含一个日期列,该数据集由以下内容组成:
date
0.25
0.50
0.75
1.00
1.25
1.50
1.75
2.00
2.25
(etc)
这表示年度宿舍。 我要做的是将每个季度转换为相应的值,0.25是第一季度,第二季度为0.50,依此类推。
结果看起来是一个新专栏,每个季度的值1:4。 类似:
date quarter
0.25 1
0.50 2
0.75 3
1.00 4
1.25 1
1.50 2
1.75 3
2.00 4
(etc)
我知道这可以做得很长的路(loop的恐惧),但我希望可以更简洁的代码。谢谢
I have a dataset that includes a date column consisting of the following:
date
0.25
0.50
0.75
1.00
1.25
1.50
1.75
2.00
2.25
(etc)
This indicates yearly quarters.
What I am trying to do is convert each quarter to have a corresponding value, 0.25 being the first quarter, 0.50 being the second and so on.
What the outcome would look like is a new column with values 1:4 for each year's quarter.
Something like:
date quarter
0.25 1
0.50 2
0.75 3
1.00 4
1.25 1
1.50 2
1.75 3
2.00 4
(etc)
I know this could be done a long way (the dreaded for loop) but I am hoping a more succinct bit of code is possible. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个可能的解决方案:
A possible solution:
只需
使用
(date-floor(date))
您只保留数字的小数位置。然后,您按.25
分开以查看它是什么四分之一。最后将零替换为四个。编辑
我看到我的答案与其他答案具有相同的逻辑。无论如何,我都保留它,因为解释可能会有所帮助。
Just do
With
(date-floor(date))
you keep just the decimal places of the number. Then you divide by.25
to see what quarter it is. And finally replacing zero by four.EDIT
I see my answer has same logic as the other one. I keep it anyway because the explanation might help.
将日期乘以4,以给出一个整数值并减去1给出0、1、2,...。然后将其余部分除以4并添加1个。我们在此下方提出的解决方案中最短的解决方案,本节中的解决方案同样一般,并且不需要连续或从第一季度开始。
请注意,x %% 4表示除以4和x %% 1之后的其余部分是除以1的剩余部分,即分数部分。
另一种选择是将一个因素转换为一个因素,并采用整数级别的
另一种方法是在动物园中使用年度QTR类。它代表年度/季度的日期,使用年度加上0、1/4、1/2和3/4的年份。
尽管有点费力,这很简单:
连续季度,
如果我们知道四分之一是连续的,并且从第一季度开始,我们可以将序列1、2、3、4重复到这样的长度。虽然不太通用非常简单。
另一种方式,如果我们知道四分之一是连续的,并且从第一季度开始的是将
日期
转换为TS系列并使用周期。注意
可重现形式的输入:
Multiply the date by 4 to give a whole number value and subtract 1 giving 0, 1, 2, ... . Then take the remainder after dividing by 4 and add 1. Of the solutions we present below this one is the shortest and the solutions in this section are equally general and do not require that the quarters be consecutive or start with the first quarter.
Note that x %% 4 means the remainder after dividing by 4 and x %% 1 is the remainder after dividing by 1, i.e. the fractional part.
An alternative is to convert to a factor and take the integer levels
Yet another approach is to use the yearqtr class in zoo. It represents year/quarter dates internally using year plus 0, 1/4, 1/2 and 3/4 for the 4 quarters.
Although a bit laborious this one is quite simple:
Consecutive quarters
If we knew that the quarters were consecutive and start with the first quarter we could repeat the sequence 1, 2, 3, 4 to the required length like this. While less general it is very simple.
Another way if we knew that that the quarters were consecutive and start with the first quarter is to convert
date
to a ts series and use cycle.Note
The input in reproducible form: