Possible Duplicate:
Assigning values to a df$column based on another column in the same df
Suppose I have the data frame:
table<- data.frame(population=c(100, 300, 5000, 2000, 900, 2500), habitat=c(1,2,3,4,5,6))
Now I want to add a new column table$size with the values 1 if population< 500, 2 if 500<=population<1000, 3 if 1000<=population<2000, 4 if 2000<=population<3000, 5 if 3000<=population<=5000
I only know how to create a column with a binary TRUE/FALSE outcome conditional on the values in another column , e.g.
table$size <- (table$population<1000)
But I’m not sure to do it to get different numbers for different conditions. Can anyone provide help on this?
First of all don’t call a
data.frametable, becausetableis a base function.You can use
findInterval:I used
all.inside = TRUEsince you wanted to define 5000 as size 5 and I assume values cannot be greater than that. If they can, you could use something likev <- c(-Inf,500,1000,2000,3000,5001,Inf).