Search code examples
rduplicatestranspose

Adding duplicate values to selective rows


For the below I need to add the first value in File 2 "17:00" to the first 3 values of file 1. Then I need to add the second value in file 2 to the to the 4th, 5th and 6th row in file 1. Then I need to add the 3rd value in file 2 to the 7th, 8th and 9th value in file 1.

Please see below. Any help is appreciated

File 1
    Gen     Type    V1   
    AB      Wind    11   
    CB      Gas     12   
    YY      Wind    13   
    AB      Wind    21   
    CB      Gas     22  
    YY      Wind    23
    AB      Wind    30   
    CB      Gas     31   
    YY      Wind    32

File 2
    Time
    17:00
    17:30
    18:00

Duplicate Values in File 1 and add values to file 2. The values in file 2 needs to align fully with the values in file 1.

New File 
   Gen     Type     V1  Time:   
    AB      Wind    11  17:00 
    CB      Gas     12  17:00 
    YY      Wind    13  17:00 
    AB      Wind    21  17:30 
    CB      Gas     22  17:30
    YY      Wind    23  17:30
    AB      Wind    30  18:00 
    CB      Gas     31  18:00 
    YY      Wind    32  18:00

Solution

  • You can create a new column using the rep function to repeat each value 3 times:

    File1$Time = rep(File2$Time, each=3)
    

    To generalize this, assuming you want to repeat the available rows in File2 equally across rows of File1, you can use:

    File1$Time = rep(File2$Time, each=(nrow(File1)/nrow(File2)))
    

    *Assuming the number of rows in File1 is a multiple of the number of rows in File2