展开R中的矩阵列

时间:2013-06-17 14:12:50

标签: r matrix

我有一个矩阵“a”,如下所示:

a<-rbind(c("a1","ost1;ost2;ost3","utr;body;pro"),
      c("a2","idh1;idh2","pro;body"),
      c("a3","dnm1","body"))
>a
     [,1] [,2]             [,3]          
[1,] "a1" "ost1;ost2;ost3" "utr;body;pro"
[2,] "a2" "idh1;idh2"      "pro;body"    
[3,] "a3" "dnm1"           "body"  

我想得到像这样的矩阵“b”

     [,1] [,2]   [,3]  
[1,] "a1" "ost1" "utr" 
[2,] "a1" "ost2" "body"
[3,] "a1" "ost3" "pro" 
[4,] "a2" "idh1" "pro" 
[5,] "a2" "idh2" "body"
[6,] "a3" "dnm1" "body"

好的,明白了:

b<-do.call(rbind, (apply(a, 1, function(x) {do.call(cbind, strsplit(x,";"))})))

1 个答案:

答案 0 :(得分:1)

您的解决方案,没有不必要的括号:

do.call(rbind, apply(a, 1, function(x) do.call(cbind, strsplit(x, ";"))))

这也有效:

do.call(rbind, lapply(apply(a, 1, strsplit, ';'), do.call, what = cbind))

并非使用匿名函数(function(x){...})有任何问题,但有些人发现它更“优雅”而没有任何问题。