This is the world-famous "fizzbuzz" problem. You should be able to find lots of implementations by Googling that word. Here's a pointless collection I wrote once:
# a really dumb fizzbuzz alg competition #fbfun1 is 2.5x faster than fbfun2 # fbfun3 is 10x faster than fbfun1 # fbfun1 is 2x faster than fbfun4 # fbfun5 is 20x faster than fbrun3 # Those are user times; in most cases the system time is very small indeed. fbfun1 <- function(xfoo) { xfoo<-1:xfoo fbfoo <- 1+(!as.logical(mod(xfoo,3)))*(as.logical(mod(xfoo,5))) + 2*(as.logical(mod(xfoo,3)))*(!as.logical(mod(xfoo,5)))+3*(!as.logical(mod(xfoo,3)))*(!as.logical(mod(xfoo,5))) fbbar <- unlist(lapply(fbfoo, function(x) switch(x,0,'fizz','buzz','fizzbuzz'))) return(fbbar) } fbfun3 <- function(xfoo) { xfoo<-1:xfoo fbfoo <- 1+(!as.logical(mod(xfoo,3)))*(as.logical(mod(xfoo,5))) + 2*(as.logical(mod(xfoo,3)))*(!as.logical(mod(xfoo,5)))+3*(!as.logical(mod(xfoo,3)))*(!as.logical(mod(xfoo,5))) fbtab<-cbind(1:4,c('','fizz','buzz','fizzbuzz')) fbbar <- fbtab[fbfoo,2] return(fbbar) } # can I do it with recycled vectors, e.g. c('','','fizz') and c('','','','','buzz') ? fbfun4 <- function(xfoo) { fiz<- rep(c('','','fizz'),length.out=xfoo) buz<-rep(c('','','','','buzz'),length.out=xfoo) fbbar <- unlist(lapply(1:xfoo, function(j)paste(fiz[j],buz[j]) ) ) return(fbbar) } # or completely sleazy: fbfun5 <- function(xfoo) { fiz<- rep(c('','','fizz','','buzz','fizz','','','fizz','buzz','','fizz','','','fizzbuzz'),length.out=xfoo) return(fiz) } -- View this message in context: http://r.789695.n4.nabble.com/Help-with-combining-functions-tp4678212p4678272.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help@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.