2016-03-14 117 views
-1

我想運行一個logit迴歸與國家明智的刪除R.說我有一個數據框與四個變量隨着時間的推移:year,countryid(1-12),gdp和人口。我想找出一種方法來運行12個不同的迴歸,每個去除一個國家,看看每個迴歸的效果是什麼。我一直在試圖編寫一個循環,將矢量中的係數下降,但沒有取得任何成功。迴歸與國家明智的刪除

任何幫助將不勝感激!

+1

請出示你的一些努力。 – Heroka

+1

使用'iris',像這樣:'lapply(levels(iris $ Species),function(x)lm(Sepal.Length〜Sepal.Width,data = iris [iris $ Species!= x,]))''。你可以獲得不同的'data.frame's,並移除感興趣的變量的級別,並從每個變量中運行一個線性模型('lm')。猜猜你可以將這個想法適應你的實際數據。 – nicola

回答

1

這裏有一個答案,你需要編輯一點具有確切變量工作,你必須

data(mtcars) 


y_var<-'mpg' 
x_vars<-setdiff(names(mtcars),y_var) 

for(i in x_vars){ 

    variables<-setdiff(x_vars,i) 
    fm <- as.formula(paste(y_var, " ~", paste(variables, collapse = "+"))) 
    linear_model<-glm(fm, data = mtcars) 
    assign(paste0('model_wout_',i),linear_model) #this will store your different linear models so you can call them with `summary(model.name)` 

} 

這也是一個線性模型 - 需要添加「二項」,使之分對數...

+0

OP想要刪除行,而不是列。 –

0
variables <- c("year", "countryid1", "id2", ..., "id12", "gdp", "population") 

for (i in 2:13) { 
variables.to.fit <- variables[-i] 
} 

然後你必須把你的logit放在這個循環中。在每個循環中。這會在每個drop中刪除每個id變量。

+0

歐特專門說有四列... – Heroka

0

下面是我該怎麼做。

假數據:

的 '國家'
set.seed(123) 
nobs=500 
dat <- data.frame(y = rbinom(nobs,1,0.5), 
        var1=rnorm(nobs), 
        var2=sample(LETTERS[1:12],nobs,T)) 

矢量:型號

countries <- unique(dat$var2) 
names(countries) <- countries 

名單(使提取的東西后容易):

models <- lapply(countries, function(x){ 
    fit <- glm(y~var1+var2, data=dat[dat$var2!=x,], family=binomial) 
    fit 
}) 
+0

這工作完美!非常感謝! –