r - 在 R 中展开几列

标签 r dplyr tidyr

我的数据框看起来像:

        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/

相关文章:

R 包 "spatstat": How do you get standard errors for non-smooth terms in a poisson process model (function: ppm) when use. gam=TRUE?

r - 将数据帧行转换为字符向量时出错

r - 将列引用写入 group_by 的函数

R:将 mutate 调用从处理三个二进制变量调整为处理 n 个二进制变量

r - 命名向量的 tidyr enframe vs pivot_longer

r - 如何通过将现有行的值与 R dplyr 组合来将行添加到数据帧

r - 如何根据特定序列中出现的值对列进行变异?

r - r中的集群表示树状图替代方案

r - 将数据框转换为数据框的命名列表,其名称来自 R 中的列

在数据帧的列中紧跟其后用数字替换前导 0