Search code examples
rdataframespatialrscriptrdata

Select rows from a dataframe based on a condition and then assign a priority number to them in a new column


I have a data set which has information on number of cases of an event reported in each grid.

no of cases grid number
12 454
22 345
34 67

My task is to assign priorities to each of the grid boxes based on the number of cases which appear in them. So if the grid number 67 has 34 cases, that will be assigned priority 1. grid number 345 will be 2, and so on. The result should be something like the below.

no of cases grid number priority
34 67 1
22 345 2
12 454 3

If there happens to be a tie in assigning the priority number (if two different grids report equal number of cases) the priority should be assigned based on the sum of cases adjacent to the grid of interest. I hope I was able to convey my question clearly.

Being an absolute beginner in R, I am struggling to even begin doing this.

Will really appreciate some help here.

Thank you all!


Solution

  • Is this what you are looking for?

    df = data.frame("no_of_cases" = c(12,22,34), "grid_number" = c(454,345,67))
    
    df %>% arrange(desc(no_of_cases)) %>% mutate("priority" = rank(-no_of_cases))