简体   繁体   English

如何根据日期范围在数据框中创建列?

[英]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.

相关问题 如何根据列之一中的值(日期)删除数据框中的行? - How do I delete rows in a data frame based on the value (date) in one of the columns? 如何根据日期范围和小时范围过滤数据框 - how filter data frame based on a date range and hour range 如何从具有 3 列的数据框在 R 中创建数组? - How Do I Create an Array in R from a Data Frame with 3 Columns? 如何将数据框创建到具有两列的边缘列表中? - How do I create a data frame into an edgelist with two columns? 如何根据r中的日期范围对数据进行子集化? - How do I subset data based on a date range in r? 如何查找第一个 DF 中的日期是否在另一个数据框中的日期范围内? - How do I find if a date in the first DF falls within the range of dates in another data frame? 如何将一列添加到数据框中,并用字母代表另一列中的日期范围 - How do I add a column to data frame with a letter representing a date range in another column 如何根据 R 中的列值范围拆分数据框? - How do I split a data frame based on range of column values in R? 基于第二数据帧中的日期范围汇总R数据帧 - Summarize R data frame based on a date range in a second data frame 将日期范围内数据框某些列的值相乘,并基于 R 中另一列的值 - Multiply values of some columns of a data frame within a date range and based on the values of another column in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM