我的数据框
看起来像:
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)
关于r - 在 R 中展开几列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47794115/