For a questionnaire I want to make a copy of df1 where the following two things happen with column x:

Replace missing data of x (which is coded as 0) for '-9'. So all the 0 must become -9.

A specific part of x is coded in numbers instead of categories. I created a function to assign different categories to different values

```
categorise_losses <- function(a_vector) { a_vector = case_when(
a_vector >= 0 & a_vector < 50 ~ 1,
a_vector >= 50 & a_vector < 500 ~ 2,
a_vector >= 500 & a_vector < 5000 ~ 3,
a_vector >= 5000 & a_vector < 50000 ~ 4,
a_vector >= 50000 & a_vector < 500000 ~ 5,
a_vector >= 500000 & a_vector < 5000000 ~ 6,
a_vector >= 5000000 & a_vector < 50000000 ~ 7,
a_vector >= 50000000 & a_vector < 500000000 ~ 8)
strong texta_vector }
```

I want to apply both functions on the `crop_loss`

column and the `property_loss`

column. A part of these columns are already correct. Namely for `crop_loss`

when the `year > 2006`

and for the `property_loss`

when the `year > 1995`

So the function only need to apply for the years below. The Missing data function needs to be first

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

I want to apply this function to x in df1. I assume I need apply function but I'm not really familiar with this specific mechanism.

Read more here: https://stackoverflow.com/questions/65722666/change-values-of-columns-on-conditional-bases-missing-data-and-categorical

### Content Attribution

This content was originally published by Frank van Onna at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.