嵌套if语句-R [英] Nested if statements - R
本文介绍了嵌套if语句-R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在使用多个if语句时遇到问题.即使条件不正确,也总是从第一个条件获取输出.有人可以指出我做错了什么吗?
I am having a problem with multiple if statements. The output is always taken from the first condition, even if the condition is not correct.. Can anybody point out what am I doing wrong?
代码:
for(i in 1:length(data_model3$Gewicht)){
if (data_model3$Gewicht[i] < 1){
data_model3$LIXshipping <- 3.26
}
else if (data_model3$Gewicht[i] > 1 & data_model3$Gewicht[i] < 2){
data_model3$LIXshipping <- 3.26
}
else if (data_model3$Gewicht[i] > 2 & data_model3$Gewicht[i] < 3){
data_model3$LIXshipping <- 3.86
}
else if (data_model3$Gewicht[i] > 3 & data_model3$Gewicht[i] < 4){
data_model3$LIXshipping <- 3.86
}
else if (data_model3$Gewicht[i] > 4 & data_model3$Gewicht[i] < 5){
data_model3$LIXshipping <- 3.86
}
else if (data_model3$Gewicht[i] > 5 & data_model3$Gewicht[i] < 10){
data_model3$LIXshipping <- 4.39
}
else if (data_model3$Gewicht[i] > 10 & data_model3$Gewicht[i] < 20){
data_model3$LIXshipping <- 4.81
}
else if (data_model3$Gewicht[i] > 20 & data_model3$Gewicht[i] < 31.5){
data_model3$LIXshipping <- 6.34
}
else
data_model3$LIXshipping <- 17.09
}
输出:
count_code Gewicht LIXshipping
281 4.67 3.26
683 3.34 3.26
903 14.56 3.26
7390 14.62 3.26
2778 2.86 3.26
2778 10.37 3.26
对于某些人来说,这可能是一个完全基本的问题,但我不知道如何解决.
It might be a completely basic question for some of you, but I have no idea how to fix it.
推荐答案
这可以通过一行(对于数据+一行)来完成:
This can be done by one line (+ one line for the data):
data_model3 <- data.frame(Gewicht=1:40)
data_model3$LIXshipping <- as.numeric(as.character(cut(data_model3$Gewicht, breaks=c(0,2,5,10,20,31.5, 100), labels=c(3.26, 3.86, 4.39, 4.81, 6.34, 17.09), right=FALSE)))
这篇关于嵌套if语句-R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文