Given a list of characters, such as:
L <- list("a", "b", "c", "d")
Note that, the length of L
is not fixed.
How can I get adjacent pairs of combination, such as:
[,1] [,2]
[1,] "a" "b"
[2,] "b" "c"
[3,] "c" "d"
Actually,I do this job to get a directed matrix for further network analysis. U know, in a specific computer-mediated communication, people discuss with each other one by one, there is a sequence, new comer only reply to the latest post.
Use embed
> L <- letters[1:4]
> embed(L, 2)[, 2:1]
[,1] [,2]
[1,] "a" "b"
[2,] "b" "c"
[3,] "c" "d"
Andrie's use of embed is certainly elegant and probably more efficient. Here's a slightly more clumsy method:
> 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"
Perhaps 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With