2017-01-23 164 views
-1

我試圖從邏輯迴歸中得分客戶。在計算它們的概率後,我創建了一個包含這些變量的數據框: CUSTID,depvar,prob 接下來,我可以得到概率的十進制數。R中的If-then-else語句

> quantile(prob, p=seq(0, 1, length=11), type=5) 
     0%  10%  20%  30%  40%  50%  60%  70%  80%  90%  100% 
0.0373546 0.1990744 0.2961668 0.3748728 0.4393759 0.4970248 0.5554679 0.6162423 0.6905081 0.8007684 0.9999996 

最後,我想將十分位數附加到數據幀的末尾。這裏是我的代碼:

> #Chained if-then-else 
> if (prob <=.1990744) {decile<-10} else if (prob >.1990744) {decile<-9} else if (prob >.2961668){decile<-8} else {if (prob >.3748728) {decile<-7} else if(prob >.4393759) {decile<-6} else if (prob >.4970248){decile<-5} else {if (prob >.5554679) {decile<-4} else if(prob >.6162423) {decile<-3} else if (prob >.6905081){decile<-2} else {if (prob >.8007684) {decile<-1} else {decile=0} 
+ 

正如你看到的,我留下了一個+號,如同R的期待我輸入別的東西。我應該如何構造這個if-then-else語句?

謝謝。

+2

「+」是括號不匹配的結果。無論如何,你不能在這裏使用'if'和'else'。你可以使用向量化的嵌套'ifelse',但你應該使用'cut'或'findInterval'。 – Roland

+0

要完成@Roland評論,在對代碼進行重新格式化之後,您有兩個位於'else'和'if'之間的地方,搜索'else {if'。嘗試使用像這樣的長語句的腳本並縮進內部語句,它確實有助於確定何時不能正確關閉。 – Tensibai

回答

2

這裏您不需要ifelse。您可以使用cut來標記類別。

首先是一些示例數據,因爲你沒有提供一個可重複的例子:

set.seed(1) 
dat <- data.frame(prob = rnorm(100)) 

計算十分位數:

quant <- quantile(dat$prob, probs = seq(0, 1, length.out = 11), type = 5) 

使用cut相對於該十分位標記連續值:

dat2 <- transform(dat, decile = cut(prob, c(-Inf, quant), labels = 0:10)) 

head(dat2)  
#   prob decile 
# 1 -0.6264538  2 
# 2 0.1836433  6 
# 3 -0.8356286  2 
# 4 1.5952808  10 
# 5 0.3295078  6 
# 6 -0.8204684  2 
+0

我最後需要一個附加的括號。我有一個解決方案。 – WillCoop4

+0

感謝您的及時回覆。 – WillCoop4

-1

這是一個使用ifelse的答案,首先製作數據集:

set.seed(123) 
df <- data.frame(prob = rnorm(10, mean= 0.5, sd = 0.3), decile = NA) 

那麼這個:

attach(df) 

df$decile <-ifelse(prob <=.1990744, 10, 
     ifelse(prob <.2961668, 9, 
     ifelse(prob <.3748728, 8, 
     ifelse(prob <.4393759, 7, 
     ifelse(prob <.4970248, 6, 
     ifelse(prob <.5554679, 5, 
     ifelse(prob <.6162423, 4, 
     ifelse(prob <.6905081, 3, 
     ifelse(prob <.8007684, 2, 
     ifelse(prob <.9999996, 1, 0)))))))))) 

detach(df) 
+1

使用'attach'和'detach'會讓你的生活在大型代碼庫中變得非常困難。此外,不需要使用如此多的嵌套'ifelse'語句,因爲您可以使用'cut'。 –

+0

如果我有一個案例,我只有1或2 if-then-else,我會用它作爲我的參考。謝謝。 – WillCoop4

+0

目前還不清楚我爲什麼將此解決方案標記爲最佳解決方案。明顯的選擇是斯文的「剪切」答案。 –

1

只是爲了它爲什麼不工作的解釋:

if (prob <=.1990744) { 
    decile<-10 
} else if (prob >.1990744) { 
    decile<-9 
} else if (prob >.2961668) { 
    decile<-8 
} else { # Here 
    if (prob >.3748728) { 
    decile<-7 
    } else if(prob >.4393759) { 
    decile<-6 
    } else if (prob >.4970248) { 
    decile<-5 
    } else { 
    if (prob >.5554679) { 
     decile<-4 
    } else if(prob >.6162423) { 
     decile<-3 
    } else if (prob >.6905081) { 
     decile<-2 
    } else { # and there 
     if (prob >.8007684) { 
     decile<-1 
     } else { 
     decile=0 
     } 

你可以看到有兩個地方有一個左括號。要麼刪除它們,要麼在代碼末尾添加2來修復它。

真的,使用@Sven所示的cut,這個答案只是爲了展示爲什麼格式化你的代碼會幫助你發現問題。

+0

我同意,我之前沒有使用過裁減聲明。它有幫助。謝謝。 – WillCoop4