2013-02-05 5 views
0

3 개월 기간을 기준으로 jfm (1 월에서 3 월까지), fma (2 월에서 4 월), mam (3 월에서 5 월) ... 10 월 12 월). 회귀 변수로 여러 변수를 사용하여 이러한 모든 데이터에 대해 유사한 분석을 실행하고 싶습니다. 다음은 오염 물질 중 하나를 회귀 변수로 사용하여 두 개의 하위 집합 데이터 프레임 중 하나에 대한 분석을 실행하는 방법을 보여줍니다. 나는 모델에 별도로 입력 된 모든 오염 물질 (pm10median, pm25median, o3median 및 so2median)에 대한 분석을 실행하는 데 관심이 있습니다. 모든 데이터 프레임에 대해이 분석을 수행하려면 어떻게해야합니까? 이 부분 집합 필요가 없습니다여러 데이터 프레임에 대한 회귀

library(gamair) 
library(mgcv) 
data(chicago) 
chicago$date<-seq(from=as.Date("1987-01-01"), to=as.Date("2000-12-31"),length=5114) 


chicago$month<-as.numeric(format(chicago$date,"%m")) ## create month 
jfm <- subset(chicago, month %in% c(1:3))  ## subset data for January to March 
fma <- subset(chicago, month %in% c(2:4)) ## February to April 
mam <- subset(chicago, month %in% c(3:5)) ## March to may 


jfm$trend<-seq(dim(jfm)[1]) ## cretae a trend for specific df based on dimension of the df 
fma$trend<-seq(dim(fma)[1]) ## trend for df fma 


## Regress each pollutant separately on death for the first subset 

model1<-gam(death ~ pm10median + s(trend,k=21)+ s(tmpd,k=6) ,family=quasipoisson,na.action=na.omit,data=jfm) 

model2<-gam(death ~ pm10median + s(trend,k=21)+ s(tmpd,k=6) ,family=quasipoisson,na.action=na.omit,data=fma) 
+0

, 당신은 OND ... –

+0

@AdityaSihag 예까지, JFM, FMA, 이맘에 의해, tapply 인수를 사용할 수 있습니까? :) –

답변

0
# create a function that defines the exact regression 
# you want to run on all three-month data sets 
fun <- 
    function(y , x){ 

     # store each of the regression outputs into an object 
     a <- gam(
      death ~ pm10median + s(trend,k=21)+ s(tmpd,k=6) , 
      family = quasipoisson , 
      na.action = na.omit , 
      data = x[ x$month %in% y , ] 
     ) 
     b <- gam(
      death ~ pm25median + s(trend,k=21)+ s(tmpd,k=6) , 
      family = quasipoisson , 
      na.action = na.omit , 
      data = x[ x$month %in% y , ] 
     ) 

     # return each of the regressions as a list 
     list(a , b) 
    } 

# define which three-month groups you want to run it on 
months <- cbind(1:10 , 2:11 , 3:12) 

# now just run the function for each row in `months` 
results <- apply(months , 1 , fun , x = chicago) 

# look at the whole thing 
results 

# extract jfm, for example 
jfm <- results[[1]] 

# extract fma (and print it to the screen as well) 
(fma <- results[[2]]) 
+0

친애하는 앤서니, 멋진 코드를 보내 주셔서 감사합니다. 단일 회귀 분석기에 대한 내 데이터뿐만 아니라 샘플에서도 작동했습니다. 다른 오염 물질을 순환시키는 방법을 코드에 추가 할 수 있습니까? 나는 당신의 두 개를 좋아한다! – Meso

+0

@ user1754610 당신이 재현 할 수있는 예제를 제공 할 때까지. [이것을 읽고 질문을 편집] (http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) –

+0

샘플 chicago 데이터 세트의 변수를 참조합니다. (pm10 미디어, pm25 미디어, o3 미디어 및 so2 미디어). 내 편집을 참조하십시오. – Meso

관련 문제