My dataframe
looks like:
date nights rooms searches
1 2018-01-01 2 1 30
2 2018-01-01 2 2 1
3 2018-01-01 3 1 115
I need to expand date, rooms and searches columns by nights column . Rooms and searches do not change expanding by nights. Expanding date column by nights affects date column as follows:
date rooms searches
1 2018-01-01 1 30
2 2018-01-02 1 30
4 2018-01-01 2 1
5 2018-01-02 2 1
7 2018-01-01 1 115
8 2018-01-02 1 115
9 2018-01-03 1 115
A solution using tidyverse
.
library(tidyverse)
dt2 <- dt %>%
mutate(date = as.Date(date)) %>%
rowwise() %>%
mutate(date = map2(date, nights, ~seq(.x, .x + nights - 1, by = "day"))) %>%
unnest() %>%
select(date, rooms, searches)
dt2
# # A tibble: 7 x 3
# date rooms searches
# <date> <int> <int>
# 1 2018-01-01 1 30
# 2 2018-01-02 1 30
# 3 2018-01-01 2 1
# 4 2018-01-02 2 1
# 5 2018-01-01 1 115
# 6 2018-01-02 1 115
# 7 2018-01-03 1 115
DATA
dt <- read.table(text = " date nights rooms searches
1 2018-01-01 2 1 30
2 2018-01-01 2 2 1
3 2018-01-01 3 1 115",
header = TRUE, stringsAsFactors = FALSE)
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.