[R] Double Roop

Sarah Goslee sarah.goslee at gmail.com
Tue Jun 30 15:32:58 CEST 2015


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:
>  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
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.



-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list