vendredi 15 janvier 2021

Applying mutate based on a condition with case_when

I want to transform my dataset and created a code for that. I've one problem. In this code I need to include the condition that yr > 2006 and that the mutate function only applies for those years. I used filter but that results in the elimination of the other rows and thats not the idea. The code that I created =

Q10_tornadoes <- tornadoes %>% mutate(crop_loss = crop_loss * 1000000) %>%
  mutate (crop_loss = case_when(
  crop_loss >= 0 & crop_loss < 50 ~ 1,
  crop_loss >= 50 & crop_loss < 500 ~ 2,
  crop_loss >= 500 & crop_loss < 5000 ~ 3,
  crop_loss >= 5000 & crop_loss < 50000 ~ 4,
  crop_loss >= 50000 & crop_loss < 500000 ~ 5, 
  crop_loss >= 500000 & crop_loss < 5000000 ~ 6, 
  crop_loss >= 5000000 & crop_loss < 50000000 ~ 7, 
  crop_loss >= 50000000 & crop_loss < 500000000 ~ 8,
  crop_loss == -9 ~ -9))

Dataset = Tornadoes

num   yr mo dy     time state magnitude injuries fatalities crop_loss
1   1 1950  1  3 11:00:00    MO         3        3          0        -9
2   1 1950  1  3 11:10:00    IL         3        0          0        -9
3   2 1950  1  3 11:55:00    IL         3        3          0        -9
4   3 1950  1  3 16:00:00    OH         1        1          0        -9
5   4 1950  1 13 05:25:00    AR         3        1          1        -9
6   5 1950  1 25 19:30:00    MO         2        5          0        -9
  property_loss
1             6
2             5
3             5
4             4
5             3
6             5

Aucun commentaire:

Enregistrer un commentaire