R:根据日期提取数据,如果日期小于,则提取数据. [英] R: Extract data based on date, "if date lesser than"

查看:64
本文介绍了R:根据日期提取数据,如果日期小于,则提取数据.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,每个 date 都有两个值,如下所示:

I have a dataset with two values for each date like this:

    date        x   y
1   2013-05-01  1   2
2   2013-05-02  2   2
3   2013-05-03  3   2

日期的格式为 as.Date ,使用软件包 lubridate .

date is in the format as.Date, using the package lubridate.

现在,我希望具有两个值的 mean ,除了一定的时间跨度之外,在该时间跨度中,我想使用 x 的值.

Now I want to have the mean of the two values, except for a certain time span, in which I want to use the values of x.

我尝试了以下操作:

mean=(x+y)/2

newdata=ifelse((data$date < 2013-10-01 | date$date > 2014-04-09), mean, x)

但是如果只对所有日期采用 mean .

but if will just take the mean for all dates.

是否可以使用比关系大/小的日期?有关如何进行这项工作的任何建议?

Is it possible to use greater/lesser than relationships for dates? Any suggestions on how to make this work?

预先感谢

推荐答案

您似乎没有将比较值转换为日期.另外,您用于比较的日期不会排除您提供的数据框中的任何日期,因此我希望每次都选择均值.

It looks like you are not casting the comparison values as dates. Also the dates you used for comparison don't exclude any of the dates in the dataframe you provided so I'd expect the mean to be selected every time.

date <- as.Date(c('2013-05-01', '2013-05-02', '2013-05-03'))
x    <- c(1, 2, 3)
y    <- c(2, 2, 2)
mean <- (x + y)/2
df   <- data.frame(date = date, x = x, y = y)
newdata <- ifelse((df$date < as.Date('2013-05-02') | df$date > as.Date('2014-04-09')), mean, x)

newdata

我将条件中的日期更改为更具选择性,并得到了 1.5 2.0 3.0 .它从 mean 中选择第一个值,并从 x 中选择其他值,这与我在 ifelse()中使用的条件一致.

I changed the dates in the condition to be more selective and I got 1.5 2.0 3.0. It selects the first value from mean and the others from x which agrees with the condition I used in the ifelse().

这篇关于R:根据日期提取数据,如果日期小于,则提取数据.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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