[R] Nested For Loop

arun smartpink111 at yahoo.com
Sat Jun 30 02:18:25 CEST 2012


Hi,

I knew that you already got many replies.

Here is my contribution.
dat1<-paste0(expand.grid(d,e)$Var1,expand.grid(d,e)$Var2,sep="")

or
dat2<-as.vector(rbind(paste0(d,e[1],sep=""),paste0(d,e[2],sep=""),paste0(d,e[3],sep="")))


#Still Bert's one line is the shortest


A.K.



----- Original Message -----
From: arun.gurubaramurugeshan <arun.gurubaramurugeshan at autozone.com>
To: r-help at r-project.org
Cc: 
Sent: Thursday, June 28, 2012 5:03 PM
Subject: [R] Nested For Loop

I am creating a nested for loop and following are the codes I'm using, but I
am not acheiving what I want.

I have a vector 

d<-151:159

I have another vector

e<-e<-c("apple", "orange", "banana")

I need to create f as
151apple
151orange
151banana
.
.
159apple
159orange
159banana

Here is how I wrote nested for loop...

for (i in 1:length(d))
{ for (j in 1:length(e))
{
x[j]<-paste(d[i],e[j],sep="")
print(x[j])
}
}

The result of the above codes is....

> for (i in 1:length(d))
+ { for (j in 1:length(e))
+ {
+ x[j]<-paste(d[i],e[j],sep="")
+ print(x[j])
+ }
+ }
[1] "151apple"
[1] "151orange"
[1] "151banana"
> 


What do I need to do this looping produce the desired result.

Thanks
Arun
----





--
View this message in context: http://r.789695.n4.nabble.com/Nested-For-Loop-tp4634804.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
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