I have a df indicating start and end dates of a certain observation. Often this observation lasts longer than one day, giving it a value of >0 in the "duration" column. I want to add the days which lay in between "start" and "end" ("duration") as new rows into my df. How can I do this?
Example df
df <- data.frame(start_date = c(as.Date("1/1/2020", "1/25/2020", "2/11/2020")),
end_date = c(as.Date("1/5/2020", "1/26/2020", "2/13/2020")),
duration = c(4, 1, 2))
You can simply subtract df$start_date
from df$end_date
:
df$end_date - df$start_date
#Time differences in days
#[1] 4 1 2
or use difftime
:
difftime(df$end_date, df$start_date, "days")
#Time differences in days
#[1] 4 1 2
To get a sequence of dates use seq
:
do.call(c, Map(seq, df$start_date, df$end_date, by=1))
# [1] "2020-01-01" "2020-01-02" "2020-01-03" "2020-01-04" "2020-01-05"
# [6] "2020-01-25" "2020-01-26" "2020-02-11" "2020-02-12" "2020-02-13"
Data:
df <- data.frame(start_date = as.Date(c("1/1/2020", "1/25/2020", "2/11/2020"), "%m/%d/%y"),
end_date = as.Date(c("1/5/2020", "1/26/2020", "2/13/2020"), "%m/%d/%y"),
duration = c(4, 1, 2))
Are you looking for such a solution?
library(dplyr)
library(lubridate)
df %>%
mutate(start_date = mdy(start_date),
end_date = mdy(end_date)) %>%
mutate(duration = end_date - start_date)
data:
df <- data.frame(start_date = c("1/1/2020", "1/25/2020", "2/11/2020"),
end_date = c("1/5/2020", "1/26/2020", "2/13/2020"))
Output:
start_date end_date duration
1 2020-01-01 2020-01-05 4 days
2 2020-01-25 2020-01-26 1 days
3 2020-02-11 2020-02-13 2 day
Are you looking for this solution?
library(tidyverse)
df %>%
mutate(date = map2(start_date, end_date, seq, by = '1 day')) %>%
unnest(date) -> result
result
# start_date end_date duration date
# <date> <date> <dbl> <date>
# 1 2020-01-01 2020-01-05 4 2020-01-01
# 2 2020-01-01 2020-01-05 4 2020-01-02
# 3 2020-01-01 2020-01-05 4 2020-01-03
# 4 2020-01-01 2020-01-05 4 2020-01-04
# 5 2020-01-01 2020-01-05 4 2020-01-05
# 6 2020-01-25 2020-01-26 1 2020-01-25
# 7 2020-01-25 2020-01-26 1 2020-01-26
# 8 2020-02-11 2020-02-13 2 2020-02-11
# 9 2020-02-11 2020-02-13 2 2020-02-12
#10 2020-02-11 2020-02-13 2 2020-02-13
You can drop the columns that you don't need using select
.
data
df <- structure(list(start_date = structure(c(18262, 18286, 18303),class = "Date"),
end_date = structure(c(18266, 18287, 18305), class = "Date"),
duration = c(4, 1, 2)), class = "data.frame", row.names = c(NA, -3L))
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.