Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading