[R] Trying to do aseries of subsets with function or for loop

John Kane jrkrideau at yahoo.ca
Mon Aug 7 18:46:20 CEST 2006


I want to  calculate the "scat" etc,  values for each
level of id, output a  vector of these values that is
a <- c(scat, sdog, srat, sbat ) and do an rbind on
them.  Each level of id has  a different value of
rate.  
 
So far it it looks to me like I can do this by a
series of repeated subsets of Df butI would think that
I should be able to do this with a function but I am
not 
having any luck.  Thus far, I'm not even sure if the
function is doing anything

The other approach seems to be a for loop but I don't
see how to handle it there either.  I am sure I have
seen something about exporting multiple .csv files a
couple of days ago that would be relevant but I cannot
find it. 

Can anyone suggest anything?

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)

Df <- data.frame(cbind(site, id, cata, catb, doga,
dogb, rata, ratb, bata, batb))
Df
attach(Df)
rate <- c(2,3,4,5,6,7,8,9)
st <- Df$site

prog <- function ( y, z) { df <-subset(Df, site == y)
detach(Df)
attach(df)
scat <- sum(c(cata,catb), na.rm=T)* z
sdog <- sum(c(doga,dogb), na.rm=T)* z
srat <- sum(c(rata,ratb), na.rm=T)* z
sbat <- sum(c(bata,batb), na.rm=T)* z
san <- c(scat,sdog, srat,sbat)
detach(df)
attach(Df)
}
prog(st, rate)



More information about the R-help mailing list