Using R, I need to duplicate a set of dates. For example, if my dataset was:
Date | Count
1/1/2020 | 5
What I want to be able to do is have the following in a single column:
Date
1/1/2020
1/1/2020
1/1/2020
1/1/2020
1/1/2020
Using R, I need to duplicate a set of dates. For example, if my dataset was:
Date | Count
1/1/2020 | 5
What I want to be able to do is have the following in a single column:
Date
1/1/2020
1/1/2020
1/1/2020
1/1/2020
1/1/2020
We can use uncount
library(dplyr)
library(tidyr)
df1 %>%
uncount(Count) %>%
as_tibble
# A tibble: 5 x 1
# Date
# <fct>
#1 1/1/2020
#2 1/1/2020
#3 1/1/2020
#4 1/1/2020
#5 1/1/2020
If the column 'Count' is not numeric, it would show the error message because weights should be numeric
df1 %>%
uncount(as.character(Count))
Error:
weightsmust evaluate to a numeric vector
The OP mentioned that there are NA elements. In that case, use replace_na to replace the NA elements to 0 and then apply the uncount
df1 %>%
uncount(replace_na(Count, 0))
df1 <- data.frame(Date = "1/1/2020", Count = 5)