[R] Generate Variable Length Strings from Various Sources

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Sat Jan 18 19:13:40 CET 2014


People who subscribe to an avoid-for-loops "mantra" are often missing the point. Converting for loops to indexing can often yield speed improvements. Converting for loops to apply functions does not improve speed. (If you think it does, you are probably handling memory allocation differently.) Worse, in some cases it can reduce readability, so doing it because of a "mantra" can actually harm your code.

Also, posting in HTML is hardly the "R-help way" (see the Posting Guide).
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

Burhan ul haq <ulhaqz at gmail.com> wrote:
>Hi Rainer,
>
>Thanks for the tip.
>
>Your suggestion works perfectly, however as per the R Mantra of
>avoiding
>for loops,  I propose the following this alternate:
>
># number of strings to be created
>n <- 50
>
># random length of each string
>v.length = sample( c( 2:4), n, rep = TRUE )
>
># letter sources
>src.1 = LETTERS[ 1:10 ]
>src.2 = LETTERS[ 11:20 ]
>src.3 = "z"
>src.4 = c( "1", "2" )
>
># turn into a list
>src <- list( src.1, src.2, src.3, src.4 )
>
>my.g = function(len,src)
>{
>  my.s = src[[ sample( 1:4, 1 ) ]]
>  tmp = sample(my.s,len,rep=TRUE)
>  n1 = paste(tmp,collapse="")
>  n1
>} # end
>
>sapply(v.length,my.g,src)
>
>
>// Cheers.
>
>	[[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.




More information about the R-help mailing list