Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Get Adjacent Pairs of Combination Using R?

Tags:

r

combinations

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.

like image 261
Frank Wang Avatar asked Aug 25 '11 15:08

Frank Wang


3 Answers

Use embed

> L <- letters[1:4]
> embed(L, 2)[, 2:1]
     [,1] [,2]
[1,] "a"  "b" 
[2,] "b"  "c" 
[3,] "c"  "d" 
like image 99
Andrie Avatar answered Sep 23 '22 13:09

Andrie


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" 
like image 27
IRTFM Avatar answered Sep 20 '22 13:09

IRTFM


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.

like image 21
Chase Avatar answered Sep 20 '22 13:09

Chase