[R] Getting data out of a loop

John Kane jrkrideau at yahoo.ca
Wed Aug 9 13:59:02 CEST 2006


My thanks to, in order of the postings appearance at
my reader, Jim Holtman, Andrew Robinson & Neuro
LeSuperHéros for thre different and very useful
solutions to my problem.  Your help is greatly
appreciated.



--- Neuro LeSuperHéros <neuro3000 at hotmail.com> wrote:

> I'd create an empty dataframe prior to the loop.
> 
> cata <- c( 3,5,6,8,0, NA)
> catb <- c( 1,2,3,4,5,6)
> doga <- c(3,5,3,6,4, 0)
> dogb <- c(2,4,6,8,10, 12)
> rata <- c (NA, 5, 5, 4, 9, 0)
> ratb <- c( 1,2,3,4,5,6)
> bata <- c( 12, 42,NA, 45, 32, 54)
> batb <- c( 13, 15, 17,19,21,23)
> id <- c('a', 'b', 'b', 'c', 'a', 'b')
> site <- c(1,1,4,4,1,4)
> mat1 <-  cbind(cata, catb, doga, dogb, rata, ratb,
> bata, batb)
> Df <- data.frame(site, id, mat1)
> nn <- levels(Df$id)
> 
> Df
> nn
> rate <- c(2,3,4)
> 
> Result <- data.frame(matrix(NA,length(nn),4))
> for (i in 1: length(nn)) {
> dd<- subset(Df, id==nn[i])
> scat <- sum(c(dd$cata,dd$catb), na.rm=T)
> sdog <- sum(c(dd$doga,dd$dogb), na.rm=T)
> srat <- sum(c(dd$rata, dd$ratb), na.rm=T)
> sbat <- sum(c(dd$bata,dd$batb), na.rm=T)
> sss <- c(scat,sdog, srat,sbat) * rate[i]
> Result[i,] <- sss
> print(sss)
> }
> Result
> 
> 
> 
> >From: John Kane <jrkrideau at yahoo.ca>
> >To: R R-help <r-help at stat.math.ethz.ch>
> >Subject: [R] Getting data out of a loop
> >Date: Tue, 8 Aug 2006 18:00:23 -0400 (EDT)
> >
> >A stupid question but I just cannot see how to do
> >this.
> >
> >I have a loop that does some calculations and puts
> the
> >results in a vector for each iteration, but I
> cannot
> >see how to get the data out of the loop in such a
> way
> >that I can use it.  I can print it but how do I get
> it
> >into a set of vectors or what ever.
> >
> >Any help gratefully received.  Thanks
> >
> >Example
> >
> >cata <- c( 3,5,6,8,0, NA)
> >catb <- c( 1,2,3,4,5,6)
> >doga <- c(3,5,3,6,4, 0)
> >dogb <- c(2,4,6,8,10, 12)
> >rata <- c (NA, 5, 5, 4, 9, 0)
> >ratb <- c( 1,2,3,4,5,6)
> >bata <- c( 12, 42,NA, 45, 32, 54)
> >batb <- c( 13, 15, 17,19,21,23)
> >id <- Cs(a,b,b,c,a,b)
> >site <- c(1,1,4,4,1,4)
> >mat1 <-  cbind(cata, catb, doga, dogb, rata, ratb,
> >bata, batb)
> >Df <- data.frame(site, id, mat1)
> >nn <- levels(Df$id)
> >
> >Df
> >nn
> >rate <- c(2,3,4)
> >
> >for (i in 1: length(nn)) {
> >dd<- subset(Df, id==nn[i])
> >scat <- sum(c(dd$cata,dd$catb), na.rm=T)
> >sdog <- sum(c(dd$doga,dd$dogb), na.rm=T)
> >srat <- sum(c(dd$rata, dd$ratb), na.rm=T)
> >sbat <- sum(c(dd$bata,dd$batb), na.rm=T)
> >sss <- c(scat,sdog, srat,sbat) * rate[i]
> >print(sss)
> >}
> >
> >______________________________________________
> >R-help at stat.math.ethz.ch 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