Adding a new column in R data frame with values conditional on values of another column
dataframe, r
Solution
First of all don't call a `data.frame` `table`, because `table` is a base function.
You can use `findInterval`:
df <- data.frame(population=c(100, 300, 5000, 2000, 900, 2500),
habitat=c(1,2,3,4,5,6))
v <- c(-Inf,500,1000,2000,3000,5000)
df$size <- findInterval(df$population,v,all.inside = TRUE)
population habitat size
1 100 1 1
2 300 2 1
3 5000 3 5
4 2000 4 4
5 900 5 2
6 2500 6 4
I used `all.inside = TRUE` since you wanted to define 5000 as size 5 and I assume values cannot be greater than that. If they can, you could use something like
`v <- c(-Inf,500,1000,2000,3000,5001,Inf)`.
Problem
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?