在R中展开几列

在R中展开几列,r,dplyr,tidyr,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 我需要展开“日期、房间和按夜搜索”列。房间和搜索不会因夜间而改变。按夜晚展开日期列会对日期列产生

我的
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
库(tidyverse)
dt2%
变异(日期=as.date(日期))%>%
行()
变异(日期=map2(日期,夜晚,~seq(.x,.x+夜晚-1,by=“day”)))%>%
unest()%>%
选择(日期、房间、搜索)
dt2
##tibble:7 x 3
#日期室搜索
#            
# 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)

dt您希望重复的次数是
nights
还是
nights+1
nights。我刚刚编辑过,但不一样。这些帖子没有规则地扩展数据列。请参阅此处发布的解决方案:例如
df[rep(row.names(df),df$nights),]
@www.IMO这应该足够了,但我重新打开了它,以防引用不符合QI更新我的答案,从而取消使用
lubridate
包,因为此包中的功能不是严格要求的。