如何将一列从一个矩阵插入另一个矩阵?

时间:2014-09-19 18:28:46

标签: r matrix

例如,我有两个矩阵A(5X5),B(5X2)。 现在我想提取B中的第二列,并将其插入A中的第二列,使A成为5X6矩阵。

1 个答案:

答案 0 :(得分:2)

您可以使用cbind

执行此操作
set.seed(1)
matA <- matrix(rnorm(25), 5, 5)
matB <- matrix(rnorm(10), 5, 2)


cbind(matA[,1], matB[,2], matA[,2:5])

示例:

matA
#           [,1]       [,2]       [,3]        [,4]        [,5]
#[1,] -0.6264538 -0.8204684  1.5117812 -0.04493361  0.91897737
#[2,]  0.1836433  0.4874291  0.3898432 -0.01619026  0.78213630
#[3,] -0.8356286  0.7383247 -0.6212406  0.94383621  0.07456498
#[4,]  1.5952808  0.5757814 -2.2146999  0.82122120 -1.98935170
#[5,]  0.3295078 -0.3053884  1.1249309  0.59390132  0.61982575


matB
#            [,1]        [,2]
#[1,] -0.05612874  1.35867955
#[2,] -0.15579551 -0.10278773
#[3,] -1.47075238  0.38767161
#[4,] -0.47815006 -0.05380504
#[5,]  0.41794156 -1.37705956


cbind(matA[,1], matB[,2], matA[,2:5])

#           [,1]        [,2]       [,3]       [,4]        [,5]        [,6]
#[1,] -0.6264538  1.35867955 -0.8204684  1.5117812 -0.04493361  0.91897737
#[2,]  0.1836433 -0.10278773  0.4874291  0.3898432 -0.01619026  0.78213630
#[3,] -0.8356286  0.38767161  0.7383247 -0.6212406  0.94383621  0.07456498
#[4,]  1.5952808 -0.05380504  0.5757814 -2.2146999  0.82122120 -1.98935170
#[5,]  0.3295078 -1.37705956 -0.3053884  1.1249309  0.59390132  0.61982575