1

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

1 Answers1

1

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: weights must 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))

data

df1 <- data.frame(Date = "1/1/2020", Count = 5)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • When I attempt using uncount, I receive the following error `"Error: weights must evaluate to a numeric vector"` – Joseph Wooster Apr 03 '20 at 23:35
  • @JosephWooster ii assume the 'Count' column to be `numeric` class and not character – akrun Apr 03 '20 at 23:35
  • that was my problem. The column was a character as it was holding a value of "NA". Replacing NA with 0s allowed me to run uncount. Thank you for the quick help!! – Joseph Wooster Apr 03 '20 at 23:40
  • @JosephWooster If you could convert the 'Count' to `numeric`, it should work i.e. `df1 %>% mutate(Count = as.numeric(as.character(Count))) %>% uncount(Count))` – akrun Apr 03 '20 at 23:40