0

I am creating a new column called Damage_new, but feel this way is slugish.

Can someone help with a simple way to achieve the following

MyData$Damage_new[0<=MyData$Damage & MyData$Damage<=30] <- 0
MyData$Damage_new[40<=MyData$Damage & MyData$Damage<=50] <- 1
MyData$Damage_new[60<=MyData$Damage & MyData$Damage<=70] <- 2
MyData$Damage_new[80<=MyData$Damage & MyData$Damage<=100] <- 3

Thank you in advance.

1 Answers1

0

There is probably a function that does this, but i don't know. So doing it with a loop:

cond = cbind(c(0,40,60,80), c(30,50,70,100), c(0,1,2,3))
for(i in 1:nrow(cond)){
  MyData$Damage_new[cond[i,1]<=MyData$Damage & MyData$Damage<=cond[i,2]] = cond[i,3]}

You could generalize it a bit more by creating cond with seq, than you can easily change the condition (as long as it follows a PA sequence):

cond = cbind(c(0,seq(40,80,20)), c(seq(30,70,20),100), seq(0,3,1))