简体   繁体   中英

How do I create columns in a data frame based on a date range?

I have a date range:

start_date <- "2019-01-01"
end_date <- "2019-01-05"

range <- seq(as.Date(start_date), as.Date(end_date), by = 1)

And an empty data frame:

output <- data.frame()

How can I create new columns within the data frame based on the date range, with each column representing a day in the range?

The desired outcome is this (values are 0 for example purposes only):

   2018.01.01  2018.01.02  2018.01.03  2018.01.04  2018.01.05
1           0           0           0           0           0
2           0           0           0           0           0
3           0           0           0           0           0
4           0           0           0           0           0
5           0           0           0           0           0

I would have thought that something like this might have worked, but it doesn't:

for(i in range){
  output$i <- i
}

Where am I going wrong?

One option is replicate

l1 <- length(range)
setNames(data.frame(replicate(l1, data.frame(col1 = rep(0, l1)))), range)

Or using rep

data.frame(setNames(rep(list(rep(0, l1)), l1), range), check.names = FALSE)

Or use the matrix route

as.data.frame( matrix(0, l1, l1, dimnames = list(NULL, 
           as.character(range))), check.names = FALSE)

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