0

I am looking to apply an if else statement for each row in a dataset for a specific column in R. I want to have it loop through every row and check the value in a certain column to be greater or less than 150, and then assign a 1 or a 0 in a new column based on this. Below is the code that I am currently working with, when run however, only 0's are returned.

for(i in 1:nrow(RawData)){
 
  RawData[i, 5] <-   
    if(RawData$users <= 150) {
      1
    } else {
      0
    }
  
}

head(RawData)

Any advice would be great, Thanks!

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
arhomberg
  • 3
  • 2

1 Answers1

2

We don't need any loop or ifelse, just create a logical expression (which is vectorized) and coerce to integer with either + or as.integer (TRUE -> 1 and FALSE -> 0)

+(RawData$users <= 150)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I am just thinking theoretically how I might do this. I will be using the implementation for another problem, but need to know how to assign a conditional value for each row depending on the value. – arhomberg Jul 26 '21 at 18:49
  • @arhomberg do you want a `if/else` or `ifelse` – akrun Jul 26 '21 at 18:50
  • Eventually it will have multiple clauses so it will have an if then an else if, else if etc. It will essentially a sign a value based on if the number is within a certain range. like 0-50, 51-100, etc. – arhomberg Jul 26 '21 at 18:51
  • @arhomberg that you can do with `cut` i.e. `with(RawData, cut(users, breaks = c(-Inf, 0, 50, 100, 150, Inf)))` – akrun Jul 26 '21 at 18:52