Home > Software engineering >  Duplicating values from matrix next to the original value in R
Duplicating values from matrix next to the original value in R

Time:11-25

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.

CodePudding user response:

This might be faster for a large matrix as it's vectorised

mat <- matrix(rnorm(18), nrow = 3)
vmat <- as.vector(mat)
mat2 <- matrix(c(rbind(vmat, vmat)), nrow = nrow(mat), byrow = TRUE)
mat2

CodePudding user response:

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

CodePudding user response:

You can solve your problem by subsetting each column twice:

mat[, rep(1:ncol(mat), each=2)]

#       [,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
# [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

data

mat = structure(c(1.647, 0.555, 0.269, 1.125, 0.395, 2.022, 0.559, 
                  1.09, -0.184, 1.614, 0.896, 0.614, 1.578, 2.135, 1.128, 0.377, 
                  1.184, 1.036), .Dim = c(3L, 6L))
  • Related