Creating a for-loop where i identifies data by column in R -
i trying use for-loop create series of summaries of gam models of variation in capture rate of invertebrate species using smoothed term day of year (doy), , linear predictor incorporating weather (there many of these). have made function run , output model summary:
gamlin <- function(x) { m <- gam(log10e ~ s(doy) + x, data=eggseasongam) return(summary(m)) }
i think want utilize above in for-loop sequentially take x weather predictors in columns 4 through 173, struggling this. suggestions appreciated.
thanks, mike
2 approaches off top of head be:
t<-data.frame(c1=rnorm(10),c2=rnorm(10), c3=rnorm(10))
1- use formula
, allows provide character string formula
> f<-function(d,x) lm(formula(paste("c1",x,sep="~")), data=d) > f(t,"c2") call: lm(formula = formula(paste("c1", x, sep = "~")), data = d) coefficients: (intercept) c2 -0.1567 -0.4654
2- alternatively feed in column directly
> f2<-function(d,x) lm(c1 ~ d[,x], data=d) > f2(t,"c2") call: lm(formula = c1 ~ d[, x], data = d) coefficients: (intercept) d[, x] -0.1567 -0.4654
once have settled on approach dynamic regression function can put in for-loop
for(col in 4:173) f(t,col)
chances are, want use results somehow, rather print summary (perhaps take coefficients , put them in dataframe , graph them, or along lines. in case suggest checking out plyr
, reshape
packages , specficially functions melt
, ddply
within each
in case follows
library(melt) library(plyr) yvar<-t[,1] xvars<-melt(t[,-1]) > head(xvars) variable value 1 c2 -0.8200263 2 c2 -1.5359220 3 c2 -0.2107913 4 c2 -0.2950263 5 c2 0.8231989 6 c2 -0.5971358 betas<-ddply(xvars, .(variable), summarize, beta=coefficients(lm(yvar ~ value))[2])
Comments
Post a Comment