rdataframe

To store a list of dates into a vector in R


I am trying to create different date ranges based on 4 different start dates as follows:

> length<-c(250,100,30,10)
> dates<-for (i in length){
+   start_date<-Sys.Date()-i
+   print(as.Date(start_date))
+ }
[1] "2023-10-22"
[1] "2024-03-20"
[1] "2024-05-29"
[1] "2024-06-18"

Say the end point is Sys.Date()-1, which gives me:

> end_point<-Sys.Date()-1
> end_point
[1] "2024-06-27"

However, when I try to store the 4 different start dates into a list for data manipulation, NULL is returned after I do so:

> x<-(for (i in length){
+   start_date<-Sys.Date()-i
+   print(start_date)
+ })
[1] "2023-10-22"
[1] "2024-03-20"
[1] "2024-05-29"
[1] "2024-06-18"
> x
NULL

May I know, if I would like to save the outpot as a df, how should I go about it? Thanks.

Update:

> dates_vec <- c()
> for (i in length){
+   dates_vec <- c(dates_vec,as.character(start_date<-Sys.Date()-i))
+ }
> 
> start_date<-dates_vec
> end_date<-(rep(Sys.Date()-1))
> length<-as.numeric(start_date-end_date)
Error in `-.Date`(start_date, end_date) : 
  can only subtract from "Date" objects
>   
> df<-data.frame(start_date,end_date,length)
> 
> df
  start_date   end_date length
1 2023-10-22 2024-06-27    250
2 2024-03-20 2024-06-27    100
3 2024-05-29 2024-06-27     30
4 2024-06-18 2024-06-27     10

I am now able to make a df based on start_date and end_date, however, when I enter below code and there we have an error msg (however, the data-frame displays with no issues, may I ask if I have done anything wrong with the date counting?

> length<-as.numeric(start_date-end_date)
Error in `-.Date`(start_date, end_date) : 
  can only subtract from "Date" objects

Solution

  • Here is what I think you are looking for:

    dates_vec <- c()
    for (i in length){
      dates_vec <- c(dates_vec,as.character(start_date<-Sys.Date()-i))
    }
    
    
    print(dates_vec)
    
    "2023-10-21" "2024-03-19" "2024-05-28" "2024-06-17"
    

    Hope it helps!