BrendonKoum
BrendonKoum

Reputation: 25

How do I add corresponding dates to a single column of values in r?

Let's say I have a single column vector dataframe like so:

m <- matrix(sample(c(1:10), 400, replace = TRUE))
d <- as.data.frame(m)

I want to add another column to the dataframe on the left hand side with dates corresponding to each value. So for example, if I wanted to specify the date range be between 8th September 2020 and 13th September 2021. Then I want the resulting dataframe to look something like this:

date value
2020-09-09 x
2020-09-10 y
... ...
2021-10-13 z

How could I achieve this?

Upvotes: 0

Views: 50

Answers (1)

PaulS
PaulS

Reputation: 25323

Is the following what you are looking for?

library(tidyverse)
library(lubridate)

m <- matrix(sample(c(1:10), 400, replace = TRUE))
d <- as.data.frame(m)

d %>% 
  mutate(Date=seq(ymd("2021-09-09"),by="days",length.out=400), .before=V1)

Upvotes: 1

Related Questions