Skip to content
Prev 308579 / 398506 Next

Changing a for loop to a function using sapply

Hello,

You're right an _explicit_ for loop is not necessary in your case, but 
note that the *apply functions are just for loops in disguise. They are 
also the prefered R idiom.
In this case I've used ?replicate, a function of the *apply family. To 
be more readable it uses a new function, called iteratively. I believe 
that the end result looks simpler than the explicit loop version, but 
that's a matter of taste.


# Changed from character vector to function
random.string <- function(n)
     rep(NA, rs <- sample(3:n, 1, replace = TRUE))

# Unchanged
randomizeString <- function(x) {
     DNAnucleotides<- c("a","c","g","t")
     a <- sample(DNAnucleotides, 3, replace = TRUE)
     return(a)
}

# Changed to use function random.string()
DNA <- character(20)
for(i in 1:20)
     DNA[i] <- paste(unlist(sapply(random.string(21), randomizeString, 
simplify = TRUE)), collapse = "")
DNA

# New function. Note the use of lapply, not sapply
fun <- function(n){
     paste(unlist(lapply(random.string(n), randomizeString)), collapse = "")
}

DNA2 <- replicate(20, fun(21))
DNA2


Hope this helps,

Rui Barradas
Em 21-10-2012 16:14, Ed escreveu: