在R(更好的方式)中设置两个日期之间的数据帧 [英] Subset a dataframe between 2 dates in R (Better Way)

查看:120
本文介绍了在R(更好的方式)中设置两个日期之间的数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自1993年以来,我正在从巴西指数(IBOV)开始每日收益,我想找出在两个日期之间的时间段的最佳方式。

I am working with daily returns from a Brazilian Index (IBOV) since 1993, I am trying to figure out the best way to subset for periods between 2 dates.

数据框( IBOV_RET )如下:

head(IBOV_RET)
        DATE    1D_RETURN
1 1993-04-28 -0.008163265
2 1993-04-29 -0.024691358
3 1993-04-30  0.016877637
4 1993-05-03  0.000000000
5 1993-05-04  0.033195021
6 1993-05-05 -0.012048193
...

我设置2个变量 DATE1 DATE2 as dates



I set 2 variables DATE1 and DATE2 as dates

DATE1 <- as.Date("2014-04-01")
DATE2 <- as.Date("2014-05-05")

我可以使用这段代码创建一个新的子集: / p>

I was able to create a new subset using this code:

TEST <- IBOV_RET[IBOV_RET$DATE >= DATE1 & IBOV_RET$DATE <= DATE2,]

它工作,但我想知道是否有更好的方式将数据分组到2日期之间,也许使用子集。

It worked, but I was wondering if there is a better way to subset the data between 2 date, maybe using subset.

推荐答案

如@MrFlick已经指出的那样,子集的基本逻辑。一种方法可以让您更容易地将您的特定数据分组。框架将定义一个函数,它需要两个输入,例如 DATE1 DATE2 ,然后根据这些子参数返回 IBOV_RET 的子集。

As already pointed out by @MrFlick, you dont get around the basic logic of subsetting. One way to make it easier for you to subset your specific data.frame would be to define a function that takes two inputs like DATE1 and DATE2 in your example and then returns the subset of IBOV_RET according to those subset parameters.

myfunc <- function(x,y){IBOV_RET[IBOV_RET$DATE >= x & IBOV_RET$DATE <= y,]}

DATE1 <- as.Date("1993-04-29")
DATE2 <- as.Date("1993-05-04")

Test <- myfunc(DATE1,DATE2)    

#> Test
#        DATE  X1D_RETURN
#2 1993-04-29 -0.02469136
#3 1993-04-30  0.01687764
#4 1993-05-03  0.00000000
#5 1993-05-04  0.03319502

您还可以直接输入特定日期 myfunc

You can also enter the specific dates directly into myfunc:

myfunc(as.Date("1993-04-29"),as.Date("1993-05-04")) #will produce the same result

这篇关于在R(更好的方式)中设置两个日期之间的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆