简体   繁体   中英

how to add date-column to data frame

I have a data frame with many different columns (each column has 10 rows/entries) and I want to add a date-column as the first column to this data frame. The date column should end today and starts today-9. The following data frame is just a counterexample:

set.seed(123)
df <- data.frame(DE = rnorm(10, 2, 1), Wind = rnorm(10, 5, 2), Solar = rnorm(10, 2, 2))

So in this case the date-column should be c("2020-10-10", ..., "2020-10-19") .

How can I add such an cate-column which depends on the current date, like today is the 19th Oct., so the date should start today()-9 .

You can use the seq.Date function to generate such a list. Here we use the number of rows in the df but you could hard-code 10 if you prefer

date_vals <- rev(seq(Sys.Date(), by="-1 days", length.out=nrow(df)))

We start at 10, walk back a certain number of steps, and then reverse the list to get the oldest date first.

You could also specify both dates as well

date_vals <- seq(Sys.Date()-9, Sys.Date(), by="1 day") 

Then, which ever way you create the values, you can add them as the first column of your data.frame with this

df <- data.frame(dates=date_vals, df)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM