Search code examples
rmatrixreplicate

Duplicating values from matrix next to the original value in R


I have a matrix including simulated data. The data concern a repeated measurements situation, and for one variable I would like to duplicate the simulated values. The current matrix looks like this:

      [,1]  [,2]   [,3]  [,4]  [,5]  [,6]
[1,] 1.647 1.125  0.559 1.614 1.578 0.377
[2,] 0.555 0.395  1.090 0.896 2.135 1.184
[3,] 0.269 2.022 -0.184 0.614 1.128 1.036

The columns represent the repeated measurements, the rows indicate the individual. It is important that the duplicate value is next to the original value, so that it looks like this (for the first line):

      [,1]  [,2]   [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10] [,11] [,12]
[1,] 1.647 1.647 1.125 1.125  0.559 0.559 1.614 1.614 1.578 1.578 0.377 0.377

I tried some ways, but that resulted in getting the sequence of duplicates starting from column 7. Is there any way to (easily) obtain this result? Thanks in advance.


Solution

  • You can try apply in combination with rep

    t(apply( dat, 1, rep, each=2 ))
    
            V1    V1    V2    V2     V3     V3    V4    V4    V5    V5    V6    V6
    [1,] 1.647 1.647 1.125 1.125  0.559  0.559 1.614 1.614 1.578 1.578 0.377 0.377
    [2,] 0.555 0.555 0.395 0.395  1.090  1.090 0.896 0.896 2.135 2.135 1.184 1.184
    [3,] 0.269 0.269 2.022 2.022 -0.184 -0.184 0.614 0.614 1.128 1.128 1.036 1.036