[英]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): 期望的结果是这样(仅出于示例目的,值为
0
):
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
一种选择是
replicate
l1 <- length(range)
setNames(data.frame(replicate(l1, data.frame(col1 = rep(0, l1)))), range)
Or using rep
或使用
rep
data.frame(setNames(rep(list(rep(0, l1)), l1), range), check.names = FALSE)
Or use the matrix
route 或使用
matrix
路由
as.data.frame( matrix(0, l1, l1, dimnames = list(NULL,
as.character(range))), check.names = FALSE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.