R code to insert rows based on a column's value and increment it by 1

后端 未结 3 793
梦谈多话
梦谈多话 2021-01-26 05:08

I have two columns in my data as shown below. I want to insert rows based on the value in Total column. Eg. For record1, the total value is 9. So, there should be 9 records for

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-26 05:50

    Another idea:

    library(tidyr)
    library(dplyr)
    
    df %>% 
      group_by(Code) %>%
      complete(Total = full_seq(1:Total, 1))
    

    Which gives:

    #Source: local data frame [14 x 2]
    #Groups: Code [3]
    # 
    #     Code Total
    #    
    #1   Kj1.9     1
    #2   Kj1.9     2
    #3   W1.23     1
    #4   W1.23     2
    #5   W1.23     3
    #6   XS1.1     1
    #7   XS1.1     2
    #8   XS1.1     3
    #9   XS1.1     4
    #10  XS1.1     5
    #11  XS1.1     6
    #12  XS1.1     7
    #13  XS1.1     8
    #14  XS1.1     9 
    

提交回复
热议问题