1

I am provided with the following tibble..

tibble(store="store a")

..and want to expand it with the same observation 30 times, like this:

tibble(store=rep("store a", 30))

# A tibble: 30 x 1
   store  
   <chr>  
 1 store a
 2 store a
 3 store a
 4 store a
 5 store a
 6 store a
 7 store a
 8 store a
 9 store a
10 store a
# ... with 20 more rows

3 Answers3

4

You can use uncount() in tidyr.

tidyr::uncount(tibble(store = "store a"), 30)

# # A tibble: 30 x 1
#    store  
#    <chr>  
#  1 store a
#  2 store a
#  3 store a
#  4 store a
#  5 store a
#  6 store a
#  7 store a
#  8 store a
#  9 store a
# 10 store a
# # … with 20 more rows
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
  • Thats it, i was wondering wether ``tidyr:uncount()`` would ever be usefull for me. Thanks:) –  Jul 16 '20 at 13:57
  • 3
    @lucaskr please do accept this answer instead of mine because, even though we reached the same conclusion separately, DarrenTsai posted it a few seconds before me. So I will delete my answer and only this will remain. – Ric S Jul 16 '20 at 14:00
  • One more thing: The solution u gave here presumes that i initialize the tibble. The thing is, the tibble is the result of a ``group_by()%>%summarise()`` call and i want to pipe it further. By further i mean i want to extent it to 30 rows. You know any solution for that? –  Jul 16 '20 at 14:07
  • @lucaskr I think adding `%>% tidyr::uncount(30)` after your pipe code will work. – Darren Tsai Jul 16 '20 at 14:15
  • It works, great, thank you very much! :) –  Jul 16 '20 at 14:31
1

How about:

a <- tibble(store="store a")
a[rep(1, 30),]
# A tibble: 30 x 1
   store  
   <chr>  
 1 store a
 2 store a
 3 store a
 4 store a
 5 store a
 6 store a
 7 store a
 8 store a
 9 store a
10 store a
# ... with 20 more rows
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • I was looking for a tidy version to fix it, but this is definitely doing the job, Thank You! –  Jul 16 '20 at 13:38
1

Maybe replicate + rbind could work for you

do.call(rbind,replicate(30,df,simplify = FALSE))

which gives

# A tibble: 30 x 1
   store
   <chr>
 1 store a
 2 store a
 3 store a
 4 store a
 5 store a
 6 store a
 7 store a
 8 store a
 9 store a
10 store a
# ... with 20 more rows
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81