2016-12-20 1 views
0

저는 약간의 실험을하려고합니다. 동일한 변수지만 다른 트레이닝 샘플을 사용하여 R에서 몇 가지 GLM 모델을 실행하고 싶습니다.for 루프를 사용하여 여러 GLM 모델을 실행하십시오.

resp <- sample(0:1,100,TRUE) 
x1 <- c(rep(5,20),rep(0,15), rep(2.5,40),rep(17,25)) 
x2 <- c(rep(23,10),rep(5,10), rep(15,40),rep(1,25), rep(2, 15)) 
dat <- data.frame(resp,x1, x2) 

이것은 내가 사용하려고 해요 루프입니다 : 여기

몇 가지 시뮬레이션 데이터입니다

Error in InitLOogModel[i] <- glm(resp ~ ., data = trainlogis, family = binomial) : 
    object 'InitLOogModel' not found 
:

n <- 5 
for (i in 1:n) 
{ 
    ### Create training and testing data 
    ## 80% of the sample size 
    # Note that I didn't use seed so that random split is performed every iteration. 
    smp_sizelogis <- floor(0.8 * nrow(dat)) 

    train_indlogis <- sample(seq_len(nrow(dat)), size = smp_sizelogis) 

    trainlogis <- dat[train_indlogis, ] 
    testlogis <- dat[-train_indlogis, ] 

    InitLOogModel[i] <- glm(resp ~ ., data =trainlogis, family=binomial) 
} 

그러나 불행하게도,이 오류를 받고 있어요

모든 의견.

+3

'InitLOogModel'이란 무엇입니까? 목록? 그런 다음 루프 전에 정의해야합니다. 'InitLOogModel <--list()'그리고 목록에 할당 할 때 당신은'InitLOogModel [[i]] <- glm (...)}을 쓸 필요가 있지만,'lapply()' 아마. 나는 훌륭한 복제물을 찾으려고 노력할 것이다. – MrFlick

+0

감사합니다. 이것은 작동합니다 – user9292

+0

좋아하는 것을 고르는 것이 어려운 다른 질문이 있습니다. 그러나 "회귀 루프"를 검색하면 많은 제안이 나오게됩니다. 'glm()'을 사용한다는 사실은이 경우에 그렇게 중요하지 않습니다. – MrFlick

답변

1

당신이하려는 일에 caret을 사용하시기 바랍니다. 배우기에는 시간이 걸리지 만 많은 '모범 사례'가 통합되어 있습니다. 기본 사항을 배우고 나면 glm이 아닌 다른 모델을 빠르게 사용해보고 쉽게 모델을 서로 비교할 수 있습니다. 예제를 시작하기 위해 수정 된 코드가 있습니다.

## caret 
library(caret) 

# your data 
resp <- sample(0:1,100,TRUE) 
x1 <- c(rep(5,20),rep(0,15), rep(2.5,40),rep(17,25)) 
x2 <- c(rep(23,10),rep(5,10), rep(15,40),rep(1,25), rep(2, 15)) 
dat <- data.frame(resp,x1, x2) 

# so caret knows you're trying to do classification, otherwise will give you an error at the train step 
dat$resp <- as.factor(dat$resp) 

# create a hold-out set to use after your model fitting 
# not really necessary for your example, but showing for completeness 
train_index <- createDataPartition(dat$resp, p = 0.8, 
            list = FALSE, 
            times = 1) 

# create your train and test data 
train_dat <- dat[train_index, ] 
test_dat <- dat[-train_index, ] 

# repeated cross validation, repeated 5 times 
# this is like your 5 loops, taking 80% of the data each time 
fitControl <- trainControl(method = "repeatedcv", 
          number = 5, 
          repeats = 5) 

# fit the glm! 
glm_fit <- train(resp ~ ., data = train_dat, 
       method = "glm", 
       family = "binomial", 
       trControl = fitControl) 

# summary 
glm_fit 

# best model 
glm_fit$finalModel 
관련 문제