CroatiaHR
CroatiaHR

Reputation: 625

Copy rows based on column values in R

Okay so, I have the following dataset:

df = read.table(sep=",",  
    header=T,   
    text="combination,priority,boolean,value      
        0,1,True,1.4  #should be copied  
        0,2,True,2.0  #should be copied  
        1,1,True,3.2  
        1,2,True,54.2  
        2,1,False,12.1  
        2,2,False,44.1  
        ")

Is there a neat way to:

  1. copy all rows with combination == 0
  2. for each value in combination !=0
  3. AND the copied rows should take the value of the combination !=0.

Expected output:

df_new = read.table(sep=",",  
    header=T,   
    text="combination,priority,boolean,value      
        1,1,True,1.4  #copied row -> now comb==1  
        1,2,True,2.0  #copied row -> now comb==1  
        1,1,True,3.2  
        1,2,True,54.2  
        2,1,True,1.4  #copied row -> now comb==2  
        2,2,True,2.0  #copied row -> now comb==2  
        2,1,False,12.1  
        2,2,False,44.1  
        ")

Upvotes: 1

Views: 561

Answers (1)

gsolomon10
gsolomon10

Reputation: 365

Using data.table, it's a bit complex but doable:

library(data.table)
df <- setDT(df)
df_zero <- df[combination == 0]
# now combine the rows of df where combination !=0 with copies of the rows where
# combination does equal 0, taking on the non-zero combination values
df_zero <- df_zero[rep(seq_len(nrow(df_zero)), each = length(unique(df[combination!=0]$combination))), ]
df_zero[, combination := rep(unique(df[combination!=0]$combination), nrow(df[combination==0]))]
df <- rbind(df[combination!=0], df_zero)
df

     combination priority boundry       mean
  1:           1        3       f 3.57246241
  2:           1        3       t 0.22327863
  3:           1        5       t 0.05760450
  4:           2        3       f 3.47917124
  5:           2        3       t 0.26262743
 ---                                        
102:          14        5       t 0.05368306
103:          15        5       t 0.05368306
104:          16        5       t 0.05368306
105:          17        5       t 0.05368306
106:          18        5       t 0.05368306

Upvotes: 1

Related Questions