【问题标题】:Merge matrices alternating columns: x number of cols from the first and y number from the second合并矩阵交替列:来自第一个的 x 列数和来自第二个的 y 列数
【发布时间】:2017-01-27 00:09:46
【问题描述】:

希望这很简单,但解释起来似乎很棘手!

我想在 R 中组合两个矩阵,但我想将第一个矩阵的前两列作为组合矩阵的前两行,然后将第二个矩阵中的第一列作为第三列新矩阵,那么新矩阵的第 4 列和第 5 列将是第一个矩阵的第 3 列和第 4 列,依此类推。所有矩阵具有相同的行名和相同的行数

矩阵 1:

  1 2 1 2 1 2
A a b c d e f
B a b c d e f
C a b c d e f

矩阵 2:

  3 3 3
A x x x
B y y y
C z z z

所需矩阵:

  1 2 3 1 2 3 1 2 3
A a b x c d x e f x
B a b y c d y e f y
C a b z c d z e f z

在我的示例中,我需要此 (1,2)(3)(1,2)(3) 配置,但正如帖子标题所暗示的,对于来自要合并的矩阵。

【问题讨论】:

    标签: r matrix merge


    【解决方案1】:

    制作一组列索引,然后对这对矩阵的cbind-ed 版本进行子集化:

    grp1 <- 2
    grp2 <- 1
    sel <- c(rbind(
      matrix(1:ncol(mat1),ncol=ncol(mat1)/grp1),
      matrix(1:ncol(mat2),ncol=ncol(mat2)/grp2) + ncol(mat1)
    ))
    # 'sel' looks like this before coercion to a vector.
    # You can see how the alternating numbers fit together here:
    #     [,1] [,2] [,3]
    #[1,]    1    3    5
    #[2,]    2    4    6
    #[3,]    7    8    9
    cbind(mat1,mat2)[,sel]
    
      1   2   3   1   2   3   1   2   3  
    A "a" "b" "x" "c" "d" "x" "e" "f" "x"
    B "a" "b" "y" "c" "d" "y" "e" "f" "y"
    C "a" "b" "z" "c" "d" "z" "e" "f" "z"
    

    使用以下对象作为mat1mat2

    mat1 <- as.matrix(read.table(text="1 2 1 2 1 2
    A a b c d e f
    B a b c d e f
    C a b c d e f", header=TRUE, check.names=FALSE, stringsAsFactors=FALSE))
    
    mat2 <- as.matrix(read.table(text="3 3 3
    A x x x
    B y y y
    C z z z", header=TRUE, check.names=FALSE, stringsAsFactors=FALSE))
    

    【讨论】:

    • 使用rbind很好地使用R矩阵的列主要特征。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多