# [R] Getting data out of a loop

Neuro LeSuperHéros neuro3000 at hotmail.com
Wed Aug 9 01:22:02 CEST 2006

```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.
>
>
>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