ixodid
ixodid

Reputation: 2400

Sequence a group of dates in R

I wish to generate some Tidy data.

26 companies are observed everyday for 10 days. Each day a value is recorded.

The first day is: 2020/1/1

How do I create a list of dates so that the first 26 rows of the date column of the date frame is "2020/1/1" (Year, Month, Day) and the next 26 rows are "2020/1/2" etc.

Here is the data frame without the date column:

library(tidyverse)

set.seed(33)

date_chunk <- rep(as.Date("2020/1/1"), 26)

# Tidy data. 10 sequential days starting 2020/1/1/
df <- tibble(
  company = rep(letters, 10),
  value = sample(0:5, 260, replace = TRUE),
  color = "grey"
)

Upvotes: 0

Views: 519

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

For each company we can add row_number() to first date_chunk to get an incremental sequence of dates.

library(dplyr)

df %>% 
  group_by(company) %>%
  mutate(date = first(date_chunk) + row_number() - 1)

Upvotes: 1

Hasan Bhagat
Hasan Bhagat

Reputation: 405

You can try this

rep(seq(as.Date("2020-01-01"),as.Date("2020-01-10"),1),each=26)

This will return a list of dates from 2020-01-01 to 2020-01-10 where each date will be repeated 26 times

Upvotes: 2

Related Questions