using mutate_if() and the tidyverse

hi, i am undertaking a project looking tax incomes across local authorities.

I have a dataset, with tax data over the years known as tax_data

I have a column with the names of the local authorities in them, denoted by localauthority.

I want to create and if statement and a dummy column that will use a select bunch of local authorities to match up

eg something that looks like this;

if localauthority == c('Exeter', 'Oxford', 'Cambridge') then return a value of 1
if not return a value of 0

ie an if statement that will create a dummy column, where if the localauthority matches the ones listed it will return a value of 1, and if not return a value of 0.

mutate_if, would be relevant if the decision of which variable to transform was to be judged based on properties of the variable. rather, you want to do something like this.

mympg <- mutate(mpg,
                   is_in_my_group = ifelse(manufacturer %in%  c("chevrolet","dodge","ford" ),

Whenever you use a logical vector in a numeric context, R automatically converts FALSE to 0 and TRUE to 1, so in this case you don't even need the ifelse():

my_manfacturer <- c("chevrolet", "dodge", "ford")
mympg <- mutate(mpg, is_in_my_group = manufacturer %in% my_manfacturer)
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.