当前位置: 动力学知识库 > 问答 > 编程问答 >

r - I am trying to make an algorithm using if else function

问题描述:

I am trying to do some calcs using if else, but I can get it :

I have data obtained from a model, but this model tend to overestimate or underestimate the results depending of the total result.

I am presenting a simple example:

d <- c(2,2,12,10, 24,30,50,55,60)

e <- c("red", "white", "red")

car <- data.frame(d,e)

names(car) <- c("carro","Color") # variable names

if(car$carro < 10){

car$carro <- car$carro * 0.5 ##50%

} else {

if((car$carro> 10) && (car$carro < 30)){

car$carro <- car$carro * 0.9 #90%

} else {

if(car$carro >30) {

car$carro <- car$carro * 1.50 #150%

}

}

}

However, when I run the script it just assume the first condition (50%) for all the data.

网友答案:

As @user13534 already said you were comparing a list to a number. Here's how I would do this:

d <- c(2,2,12,10, 24,30,50,55,60)
e <- c("red", "white", "red")
car <- data.frame(d,e)
names(car) <- c("carro","Color") # variable names

car$carro <- lapply(car$carro, function(x) ifelse(x < 10, x * 0.5, ifelse(x < 30 && x > 10, x * 0.9, x * 1.5)))
car

  carro Color
1     1   red
2     1 white
3  10.8   red
4    15   red
5  21.6 white
6    45   red
7    75   red
8  82.5 white
9    90   red

ifelse works great for this. For readability purposes always try to leverage else if conditionals when programming instead of containing an if condition within an else condition.

网友答案:

Did you see any output in R console?

On my computer, it says:

    Warning message:
    In if (car$carro < 10) { :
      the condition has length > 1 and only the first element will be used

Basically, car$carro is a list equal to d. Since R doesn't know how to output TRUE/FALSE when comparing a list to a number, so it presumably uses the first list element, 2, to compare with 10 and output TRUE since 2 < 10. Then it just multiplies every element in car$carro by 0.5.

网友答案:

In the post, condition is not clear. For example, car$carro < 10, (car$carro> 10) && (car$carro < 30), car$carro >30 doesn't include the cases when 'carro' is 10 or 30. I am assuming that the first condition is car$carro < 10, second as (car$carro>=10) & (car$carr < 30) and third as car$carro >=30.

This can be done easily without using ifelse. We create a grouping index with cut by specifying the breaks.

  grp <- cut(car$carro, breaks=c(-Inf, 10, 30, Inf), right=FALSE, labels=FALSE)

Then, we use this numeric index to multiply the values with the 'carro' column.

  car$carro <- car$carro * c(0.5, 0.9, 1.5)[grp]
  car$carro
  #[1]  1.0  1.0 10.8  9.0 21.6 45.0 75.0 82.5 90.0
分享给朋友:
您可能感兴趣的文章:
随机阅读: