[R] Combining elements of vectors

baptiste auguie baptiste.auguie at gmail.com
Mon Jun 8 15:04:33 CEST 2009


Marie Sivertsen wrote:
> Dear list,
>
> I have a vector of elements which I want to combined each with each, but
> none with itself. For example,
>
>   
>> v <- c("a", "b", "c")
>>     
>
> and I need a function 'combine' such that
>
>   
>> combine(v)
>>     
> [[1]]
> [1] "a" "b"
>
> [[2]]
> [1] "a" "b"
>
> [[3]]
> [1] "b" "c"
>
> I am not very interested in the orders of the output items for now, and the
> form can be something differs from list, like matrix or data frame. I know
> of 'expand.grid', but it will combine each item with each item including
> itself, so not what I wants.
>
> Could you help me please.  Thank you.
>
> Mvh.,
> Marie
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>   
I guess you actually want,

[[1]]
[1] "a" "b"

[[2]]
[1] "a" "c" # not "a" "b" again

[[3]]
[1] "b" "c"


if so, try

?combn
 > combn(v,2)
     [,1] [,2] [,3]
[1,] "a"  "a"  "b"
[2,] "b"  "c"  "c"


HTH,

baptiste

-- 
_____________________________

Baptiste Auguié

School of Physics
University of Exeter
Stocker Road,
Exeter, Devon,
EX4 4QL, UK

Phone: +44 1392 264187

http://newton.ex.ac.uk/research/emag




More information about the R-help mailing list