user2341632
user2341632

Reputation: 59

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

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 the code XS1.1 with Total starting from 1 till 9. Please find below the expected output for better clarity. I am just learning the basics of R. Could you please help me with the code?

Code        Total
XS1.1       9
W1.23       3
Kj1.9       2

Output Expected:

Code     Total
XS1.1    1
XS1.1    2
XS1.1    3
XS1.1    4
XS1.1    5
XS1.1    6
XS1.1    7
XS1.1    8
XS1.1    9
W1.23    1
W1.23    2
W1.23    3
Kj1.9    1
Kj1.9    2

Upvotes: 0

Views: 3053

Answers (3)

Steven Beaupré
Steven Beaupré

Reputation: 21621

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
#   <fctr> <dbl>
#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 

Upvotes: 0

sebastiann
sebastiann

Reputation: 163

First make that data frame you expect beforehand, after that make your desired data frame:

dat <- data.frame("Code"=c("XS1.1","W1.23","Kj1.9"),"Total"=c(9,3,2))
dat2 <- data.frame("Code"=rep(dat[,1],dat[,2]),"Total"=c(seq(1:dat[1,2]),seq(1:dat[2,2]),seq(1:dat[3,2])))

Upvotes: 0

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

library(data.table)
setDT(df)[,.(Total=1:Total), code]

Or base R:

with(df, data.frame(code=rep(code, Total), Total=sequence(Total)))

Upvotes: 2

Related Questions