如何根据日期时间“自动”确定值?

时间:2022-05-16 15:20:10

Given the data:

鉴于数据:

      date <- seq(as.Date("2014-01-01"), as.Date("2014-12-31"), by = "days")
      a<-seq(1,365,1)
      b<- seq(1,365,1)

     df<-data.frame(date,a,b)

I would like to extract/subset data from a or b not by determining the date, as for instance, with:

我想从a或b中提取/子集数据而不是通过确定日期,例如,使用:

   subset<-subset(df, date >= "2014-02-01" & date <= "2014-04-13") # about 69 days

but rather:

反而:

       subset<-subset(df, date= "today"-69 & date= "today")

Everytime I run the R-Script it produces a subset between today and 69 days ago.

每次我运行R-Script时,它会在今天和69天之前生成一个子集。

1 个解决方案

#1


1  

Use Sys.Date():

使用Sys.Date():

subset(df, date >= Sys.Date()-69 & date <= Sys.Date())
[1] date a    b   
<0 rows> (or 0-length row.names)

Notes:

笔记:

  1. In your example data, you of course have no data from the last 69 days.
  2. 在您的示例数据中,您当然没有过去69天的数据。
  3. This is system-dependent so if for some reason you ever ran this on a computer that didn't know what day it was, it might cause you trouble.
  4. 这是系统相关的,所以如果由于某种原因你曾经在不知道它是哪一天的计算机上运行它,它可能会给你带来麻烦。

#1


1  

Use Sys.Date():

使用Sys.Date():

subset(df, date >= Sys.Date()-69 & date <= Sys.Date())
[1] date a    b   
<0 rows> (or 0-length row.names)

Notes:

笔记:

  1. In your example data, you of course have no data from the last 69 days.
  2. 在您的示例数据中,您当然没有过去69天的数据。
  3. This is system-dependent so if for some reason you ever ran this on a computer that didn't know what day it was, it might cause you trouble.
  4. 这是系统相关的,所以如果由于某种原因你曾经在不知道它是哪一天的计算机上运行它,它可能会给你带来麻烦。