从R中的原始值旁边的矩阵复制值

Duplicating values from matrix next to the original value in R

我有一个包含模拟数据的矩阵。数据涉及重复测量情况,对于一个变量,我想复制模拟值。当前矩阵如下所示:

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

列代表重复测量,行代表个体。重要的是重复值紧挨着原始值,因此它看起来像这样(对于第一行):

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

我尝试了一些方法,但结果得到了从第 7 列开始的重复序列。有什么方法可以(轻松)获得这个结果吗?提前致谢。

您可以尝试将 applyrep

结合使用
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

这对于大型矩阵来说可能更快,因为它是矢量化的

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

您可以通过将每列子集化两次来解决您的问题:

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

数据

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))