How can I get adjacent combination pairs using R?

Given a list of characters, for example:

L <- list("a", "b", "c", "d") 

Note that the length L not fixed.

How can I get adjacent pairs of combinations, for example:

  [,1] [,2] [1,] "a" "b" [2,] "b" "c" [3,] "c" "d" 

Actually, I am doing this work to get a directional matrix for further network analysis. U know that in a specific computer mediated communication, people discuss each other in turn, there is a sequence, the new recipient answers only the last message.

+6
source share
4 answers

Using the Andrie embedding is certainly elegant and probably more efficient. Here are some more awkward methods:

 > L<-c("a", "b", "c", "d") > L [1] "a" "b" "c" "d" > matrix(c(L[-length(L)], L[-1]), ncol=2) [,1] [,2] [1,] "a" "b" [2,] "b" "c" [3,] "c" "d" 
+5
source

Use embed

 > L <- letters[1:4] > embed(L, 2)[, 2:1] [,1] [,2] [1,] "a" "b" [2,] "b" "c" [3,] "c" "d" 
+6
source

Maybe combn :

 L<-c("a", "b", "c", "d") combn(L, 2) [,1] [,2] [,3] [,4] [,5] [,6] [1,] "a" "a" "a" "b" "b" "c" [2,] "b" "c" "d" "c" "d" "d" 

You can subset from there depending on what you need.

+1
source

You can accomplish this with cbind :

 L <- letters[1:4] cbind(head(L, -1), L[-1]) 
0
source

Source: https://habr.com/ru/post/895889/


All Articles