r - Optimal assignment of values in for loop to vector -
i have written code generate sequence of values a01, a02, a03, a04, a05, b01, b02, ..., g04, g05. know in r don't utilize loops. code works, best way handle problem?
letters <- c("a", "b", "c", "d", "e", "f", "g") numbers <- c(1:5) l <- vector() count <- 1 for(i in letters) { for(j in numbers) { l[count] <- paste(i, j, sep="") count <- count + 1 } }
the aversion loops in r overdone. if aren't working excessively big info or complex analyses, , don't need create performance code, can utilize loop. potential advantage of loop easy write without making mistakes , it's easy see how code works when come later. loops 'clash' way r works under hood, beginners isn't big deal. can utilize loop this, if that's you're comfortable with.
on other hand, wouldn't way. here way isn't advanced , yields cleaner code (see ?outer):
l <- outer(letters[1:7], as.character(c(1:5)), fun=paste, sep="") l <- as.vector(l) l # [1] "a1" "b1" "c1" "d1" "e1" "f1" "g1" "a2" "b2" "c2" "d2" "e2" "f2" "g2" "a3" # [16] "b3" "c3" "d3" "e3" "f3" "g3" "a4" "b4" "c4" "d4" "e4" "f4" "g4" "a5" "b5" # [31] "c5" "d5" "e5" "f5" "g5" r
No comments:
Post a Comment