Skip to content

Double Roop

3 messages · Peter Maclean, Sarah Goslee, David Winsemius

#
?Hi EverybodyI am trying to make?an object with??length(a) * length(b) element?using a double loop. But I am getting the last part only.??A simple script is
a <- c("A-AA", "B-BB", "C-CC")
b??? <- seq(1, 5)
pre <- NULL
post <- NULL
page <- NULLfor(j in 1:length(a)) {
?? for(i in 1:length(b)){
?????? pre[j]? <- strsplit(a[j],"-")[[1]][1] 
????????? post[j] <- strsplit(a[j],"-")[[1]][2] 
??????????? page[i] <- paste0(pre[j], b[i],post[j])? 
}}Peter Maclean
Department of Economics
UDSM
#
Hi Peter,

page is indexed by [i], so for each iteration of j you're rewriting
previous results.

You can fix that very simply, with:
a <- c("A-AA", "B-BB", "C-CC")
b    <- seq(1, 5)
pre <- NULL
post <- NULL
page <- NULL

pageno <- 1

for(j in 1:length(a)) {
   for(i in 1:length(b)){
       pre[j]  <- strsplit(a[j],"-")[[1]][1]
       post[j] <- strsplit(a[j],"-")[[1]][2]
       page[pageno] <- paste0(pre[j], b[i],post[j])
       pageno <- pageno + 1
}}

But try instead:

a <- c("A-AA", "B-BB", "C-CC")
b    <- seq(1, 5)

page <- expand.grid(b, a)
apply(page, 1, function(x)sub("-", x[1], x[2]))

Sarah

PS Please don't post in HTML; I had to unmangle your code before
working with it.

On Tue, Jun 30, 2015 at 9:04 AM, Peter Maclean via R-help
<r-help at r-project.org> wrote:

  
    
#
On Jun 30, 2015, at 6:04 AM, Peter Maclean via R-help wrote:

            
If you don't want folks here to think you have difficulty with the English language in the posting guide or with managing computer applications, you will set your mail-client to plain-text for communications to r-help. Notice that your code was a bit mangled by the HTML format. This is sometimes much more of a problem than it was in this instance. You've been posting since 2011 so really have no excuse for continuing to flout the mailing list norms:
[1] "A-AA 1" "B-BB 1" "C-CC 1" "A-AA 2" "B-BB 2" "C-CC 2" "A-AA 3"
 [8] "B-BB 3" "C-CC 3" "A-AA 4" "B-BB 4" "C-CC 4" "A-AA 5" "B-BB 5"
[15] "C-CC 5"
David Winsemius
Alameda, CA, USA