2

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
Mario M.
  • 802
  • 11
  • 26

1 Answers1

3

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)
www
  • 38,575
  • 12
  • 48
  • 84
  • I updated my answer to remove the use of the `lubridate` package because functions from this package are not strictly required. – www Dec 13 '17 at 13:50