Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating rows of data.frame in dplyr [duplicate]

Tags:

r

dplyr

I have a trouble with repeating rows of my real data using dplyr. There is already another post in here repeat-rows-of-a-data-frame but no solution for dplyr.

Here I just wonder how could be the solution for dplyr but failed with error:

Error: wrong result size (16), expected 4 or 1

library(dplyr)
    df <- data.frame(column = letters[1:4])

    df_rep <- df%>%
      mutate(column=rep(column,each=4))

Expected output

>df_rep 
    column
    #a
    #a
    #a
    #a
    #b
    #b
    #b
    #b
    #*
    #*
    #*
like image 558
Alexander Avatar asked Jul 07 '16 04:07

Alexander


1 Answers

Using the uncount function will solve this problem as well. The column count indicates how often a row should be repeated.

library(tidyverse)

df <- tibble(letters = letters[1:4])

df 
# A tibble: 4 x 1
  letters
  <chr>  
1 a      
2 b      
3 c      
4 d 

df %>%
  mutate(count = c(2, 3, 2, 4)) %>%
  uncount(count)

# A tibble: 11 x 1
   letters
   <chr> 
 1 a      
 2 a      
 3 b      
 4 b      
 5 b      
 6 c      
 7 c      
 8 d      
 9 d      
10 d      
11 d  
like image 88
MrNetherlands Avatar answered Sep 20 '22 01:09

MrNetherlands