r-在Dplyr中按计数列展开数据集



我有一个数据集,如下所示:

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

我想使用值count执行转换,也就是说,每行重复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

谢谢!

我们可以使用uncount进行复制,然后创建"计数">

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

最新更新