使用Dplyr按计数列扩展数据集

3
我有一个如下的数据集:

library(tidyverse)

df <- data.frame(
        report_date = c("2020-03-14", "2020-03-14", "2020-03-19", "2020-03-20"),
         start_date = c("2020-03-06", "2020-03-10", "2020-03-11", "2020-03-11"),
              count = c(1, 2, 1, 3)
     )

看起来像:

  report_date start_date count
1  2020-03-14 2020-03-06     1
2  2020-03-14 2020-03-10     2
3  2020-03-19 2020-03-11     1
4  2020-03-20 2020-03-11     3

我希望使用值计数来执行转换,即将每一行重复n次,例如起始行的计数。如果我展示所需结果,那么我认为这很清楚,如下所示:
df_final <- data.frame(
               report_date = c("2020-03-14", "2020-03-14", "2020-03-14", "2020-03-19",
                               "2020-03-20", "2020-03-20", "2020-03-20"),
                start_date = c("2020-03-06", "2020-03-10", "2020-03-10", "2020-03-11",
                               "2020-03-11", "2020-03-11", "2020-03-11"),
                     count = c(1, 1, 1, 1, 1, 1, 1)
            )

  report_date start_date count
1  2020-03-14 2020-03-06     1
2  2020-03-14 2020-03-10     1
3  2020-03-14 2020-03-10     1
4  2020-03-19 2020-03-11     1
5  2020-03-20 2020-03-11     1
6  2020-03-20 2020-03-11     1
7  2020-03-20 2020-03-11     1

谢谢!

1个回答

4

我们可以使用uncount来复制并创建“count”

library(dplyr)
library(tidyr)
df %>% 
    uncount(count) %>% 
    mutate(count = 1) 

-输出

 report_date start_date count
1  2020-03-14 2020-03-06     1
2  2020-03-14 2020-03-10     1
3  2020-03-14 2020-03-10     1
4  2020-03-19 2020-03-11     1
5  2020-03-20 2020-03-11     1
6  2020-03-20 2020-03-11     1
7  2020-03-20 2020-03-11     1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接