簡體   English   中英

在R中展開幾列

[英]expand several columns in R

我的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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM