根据列名称将矩阵拆分为两个数组

时间:2020-09-11 10:38:36

标签: r

我有一个像这样的矩阵

structure(c(“ cat”,“ Dog”,“ Dog1”,“ Cow”,“ E02.3”,“ E06.7”,“ E01.9”, “ E01.0”,“ Twe.03”,“ Twl.06”,“ Twl.15”,“ Twl.00”,“ CA / DO”,“ CA”, “ DO”,“ CA”),.Dim = c(4L,4L),.Dimnames = list(NULL,c(“ Name”, “ Id1”,“ Id2”,“类型”))))

我需要拆分为两个数组,像这样仅基于Type列值的Id1值

CA

   E02.3
   E06.7
   E01.0

DO

  E02.3
  E01.9

表示通用名称的CA / DO值。

2 个答案:

答案 0 :(得分:2)

使用grep

cbind(m[grep("CA", m[,"Type"]), "Id1"])
#      [,1]   
# [1,] "E02.3"
# [2,] "E01.9"
cbind(m[grep("DO", m[,"Type"]), "Id1"])
#      [,1]   
# [1,] "E02.3"
# [2,] "E06.7"
# [3,] "E01.0"

答案 1 :(得分:1)

带有strsplit

的选项
with(stack(setNames(strsplit(m1[, "Type"], "/", fixed = TRUE), 
      m1[, "Id1"])), split(as.character(ind), values))