在R中展开几列

时间:2017-12-13 13:23:52

标签: r dplyr tidyr

我的dataframe看起来像是:

        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

我需要按日夜列扩展日期,房间和搜索列。房间和搜索不会改变夜间扩展。按夜间扩展日期列会影响日期列,如下所示:

         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

1 个答案:

答案 0 :(得分:3)

使用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

数据

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)