2017-01-23 82 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