【问题标题】:Add row into a matrix if rowname not present into a list R如果行名不存在于列表 R 中,则将行添加到矩阵中
【发布时间】:2020-04-05 14:51:33
【问题描述】:

我有一个matrix_1 例如:

    Group1 Group2 Group3
Sp1 1 1 1
Sp3 1 0 0
Sp4 1 1 0
Sp5 1 0 1
Sp6 0 1 1
Sp7 0 1 1

还有一个

list_Sp=c("Sp1","Sp2","Sp3","Sp4","Sp5","Sp6","Sp7","Sp8")

我想在这个 matrix_1 中添加一个由 0 值填充的行,如果矩阵的行名中还没有出现在 list_Sp 中的 SpX。

这里 Sp2 和 Sp8 不存在,然后我添加它们:

新矩阵:

    Group1 Group2 Group3
Sp1 1 1 1
Sp3 1 0 0
Sp4 1 1 0
Sp5 1 0 1
Sp6 0 1 1
Sp7 0 1 1
Sp2 0 0 0
Sp8 0 0 0

感谢您的帮助

【问题讨论】:

    标签: r list matrix


    【解决方案1】:

    调用您的输入矩阵M,然后我们可以执行以下操作:

    # find which are new
    new_rows = list_Sp[!list_Sp %in% rownames(M)]
    
    # build a matrix with 0s in the right shape & with the right names
    new_data = matrix(0L, nrow = length(new_rows), ncol = ncol(M), 
                      dimnames = list(new_rows, colnames(M)))
    
    # "attach" it to M with rbind
    new_M = rbind(M, new_data)
    new_M
    #     Group1 Group2 Group3
    # Sp1      1      1      1
    # Sp3      1      0      0
    # Sp4      1      1      0
    # Sp5      1      0      1
    # Sp6      0      1      1
    # Sp7      0      1      1
    # Sp2      0      0      0
    # Sp8      0      0      0
    

    如果希望Sp1..Sp8有序,可以多加一行:

    new_M = new_M[order(rownames(new_M)), ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-30
      • 2022-01-15
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      • 2016-09-26
      相关资源
      最近更新 更多