[R] Generate combination of strings

Petr Savicky savicky at cs.cas.cz
Fri Apr 13 08:59:09 CEST 2012


On Thu, Apr 12, 2012 at 01:14:27PM -0700, Bart6114 wrote:
> Hey all,
> 
> I am trying to generate a number of vectors with string combinations. The
> below code solves my initial problem, however I would prefer not hardcoding
> the positions of the 'objects' as in the future the number of 'objects'
> could increase. Is there a way to loop over these objects and generate the
> same output? The same goes for the 'maxspacer'. 
> 
> Thanks a whole bunch!
> 
> Bart
> 
> code:
> 
> objects<-c('OCT','ASS','SUP')
> maxspacer<-c(2,3)
> 
> for(x in 0:maxspacer[1]){
> for(y in 0:maxspacer[2]){
> 
> combo<-c(objects[1],rep('',x),objects[2],rep('',y),objects[3])
> 
> print(combo)
> }
> }

Hi.

Try the following.

  objects<-c('OCT','ASS','SUP')
  maxspacer<-c(2,3)

  expand <- function(obj, sp)
  {
      i <- cumsum(c(1, sp+1))
      x <- rep("", times=max(i))
      x[i] <- obj
      x
  }
 
  lstsp <- lapply(maxspacer, function(x) 0:x)
  spacing <- as.matrix(rev(expand.grid(rev(lstsp))))
 
  for (i in seq.int(length=nrow(spacing))) {
      print(expand(objects, spacing[i,]))
  }

  [1] "OCT" "ASS" "SUP"
  [1] "OCT" "ASS" ""    "SUP"
  [1] "OCT" "ASS" ""    ""    "SUP"
  [1] "OCT" "ASS" ""    ""    ""    "SUP"
  [1] "OCT" ""    "ASS" "SUP"
  [1] "OCT" ""    "ASS" ""    "SUP"
  [1] "OCT" ""    "ASS" ""    ""    "SUP"
  [1] "OCT" ""    "ASS" ""    ""    ""    "SUP"
  [1] "OCT" ""    ""    "ASS" "SUP"
  [1] "OCT" ""    ""    "ASS" ""    "SUP"
  [1] "OCT" ""    ""    "ASS" ""    ""    "SUP"
  [1] "OCT" ""    ""    "ASS" ""    ""    ""    "SUP"

The functions rev() may be removed, if the order of the
output may not be exactly as in your code.

Hope this helps.

Petr Savicky.



More information about the R-help mailing list