[R] combination of different vector values

John Fox jfox at mcmaster.ca
Fri Jun 14 23:09:38 CEST 2002


Dear Jacqueline,

At 10:16 AM 6/14/2002 -0700, Ngayee.Law at celeradiagnostics.com wrote:


>I have a few vectors and I need to get all the combinations of the vector
>values.
>Normally I would use a few for-loops to do that.
>e.g  x1_c(1,3,5)
>      x2_c(2,5,6)
>      for (i in x1) {
>        for (j in x2) {
>           ...
>      }}
>
>My problem is that I don't know how many vectors there are ahead of time,
>so
>I don't know how many for-loops I need. Any ideas how to implement this?

You don't say what you want to do within the loops, but you may be able to 
adapt the following example, which puts the vectors in a list, loops over 
the list, and uses outer to generate combinations:

     > x <- 1:3
     > y <- 10*(1:3)
     > z <- 100*(1:3)
     > lst <- list(x, y, z)
     > result <- lst[[1]]
     > for (i in 2:length(lst)) result <- outer(result, lst[[i]], '+')
     > as.vector(result)
     [1] 111 112 113 121 122 123 131 132 133 211 212 213 221 222 223 231
     [17] 232 233 311 312 313 321 322 323 331 332 333

If this doesn't work, perhaps you could specify the problem in more detail.

John
-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list