Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unlist two columns while keeping the pairs of values from the columns

Tags:

r

I am trying to unlist a list in order to get a sorted (this is the point) array and i am not able to find any hint.

So, lets say this is my list:

V1<-c("Node 1","Node 3","Node 3","Node 3","Node 4","Node 4","Node 4","Node 4","Node 5","Node 7","Node 8","Node 8");
V2<-c("Node 2","Node 5","Node 6","Node 2","Node 1","Node 5","Node 7","Node 2","Node 2","Node 8","Node 6","Node 3");
try<-data.frame(V1,V2);
colnames(try)<-c("V1","V2");

Now, if I try to unlist it, this is what i get:

array(unlist(try))
 [1] "Node 1" "Node 3" "Node 3" "Node 3" "Node 4" "Node 4" "Node 4" "Node 4"
 [9] "Node 5" "Node 7" "Node 8" "Node 8" "Node 2" "Node 5" "Node 6" "Node 2"
[17] "Node 1" "Node 5" "Node 7" "Node 2" "Node 2" "Node 8" "Node 6" "Node 3"

but this is not what i wanted. I need an array which preserves the coupling of the two columns. Lets say i need to bring the firs value of V1 with the first value of V2, then second value from V1 and second value from V2 etc...and eventually have them in an array:

"Node 1","Node 2","Node 3","Node 5","Node 3","Node 6","Node 3","Node 2","Node 4","Node 1","Node 4","Node 5","Node 4","Node 7","Node 4","Node 2","Node 5","Node 2","Node 7","Node 8","Node 8","Node 6","Node 8","Node 3"

Anyone who has the solution without using a for loop? Or is that the only way?

like image 868
gabt Avatar asked Jan 06 '23 03:01

gabt


1 Answers

Even shorter:

c(t(try))
[1] "Node 1" "Node 2" "Node 3" "Node 5" "Node 3" "Node 6" "Node 3" "Node 2" "Node 4" "Node 1" "Node 4" "Node 5"
[13] "Node 4" "Node 7" "Node 4" "Node 2" "Node 5" "Node 2" "Node 7" "Node 8" "Node 8" "Node 6" "Node 8" "Node 3"
like image 74
mtoto Avatar answered Jan 27 '23 01:01

mtoto