lundi 30 avril 2018

setting multiple if statements correctly

I have difficulty to set proper nested if stament in user defined function.

My sample data is like this

test = data.frame(x=rev(0:10),y=10:20)

if_state <- function(x,y){
  if(x==min(x)&&y==max(y)){
    "good"
    }
  else
  if(max(x)/2==y[which(y==15)]/3){  #to find when x=5 and y=5 condition if it is true set class to "y==5"
    "y==5"
  }
      NA

}

   > test
    x  y
1  10 10
2   9 11
3   8 12
4   7 13
5   6 14
6   5 15
7   4 16
8   3 17
9   2 18
10  1 19
11  0 20

library(dplyr)
test%>%
  mutate(class=if_state(x,y))


    x  y class
1  10 10    NA
2   9 11    NA
3   8 12    NA
4   7 13    NA
5   6 14    NA
6   5 15    NA
7   4 16    NA
8   3 17    NA
9   2 18    NA
10  1 19    NA
11  0 20    NA

I don't know why if statement is not working correctly ?

Aucun commentaire:

Enregistrer un commentaire