3

I have a matrix "a" like the following:

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" 

I want to get a matrix "b" like this

 [,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" 

OK, get it:

b<-do.call(rbind, (apply(a, 1, function(x) {do.call(cbind, strsplit(x,";"))}))) 
2
  • 7
    Feel free to post your solution as an answer and accept it. Commented Jun 17, 2013 at 14:16
  • 2
    do.call is almost like magic :-) . Nice work. Commented Jun 17, 2013 at 14:56

1 Answer 1

1

Your solution, without the unnecessary parentheses:

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

This also works:

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

Not that there is anything wrong with using anonymous functions (function(x){...}), but some people find it more "elegant" without any.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.