0

I have a datsaset which shows tax paid by a number of different local authorities.

I want to create a dummy column, so that if I state specific local authorities in an if statement, if they match it returns a value of 1, if not it returns a value of 0.

I have tried:

mutate_if(tax_data, localauthority %in% c('Exeter', 'Glasgow', 'Oxford'), funs(dummy==1))
mutate_if(tax_data, localauthority != c('Exeter', 'Glasgow', 'Oxford'), funs(dummy==0))

Can anyone provide any help on how i can use an if statement whilst creating a dummy column to satisfy this condition?

yang
  • 719
  • 3
  • 11
josh
  • 73
  • 1
  • 5
  • try case_when , it has easy syntax – user12256545 Apr 22 '20 at 12:17
  • `mutate(tax_data, dummy = as.numeric(localauthority %in% c('Exeter', 'Glasgow', 'Oxford'))` – caldwellst Apr 22 '20 at 12:20
  • For a clearer look at `ifelse()` statements for dummy variables, look [here](https://stackoverflow.com/questions/52461445/how-to-create-a-dummy-variable-in-r-using-ifelse-command) – caldwellst Apr 22 '20 at 12:23
  • `mutate_` are used to select columns to be "mutated" on – Frank Zhang Apr 22 '20 at 12:23
  • Try `mutate(tax_data, dummy = ifelse(localauthority %in% c('Exeter', 'Glasgow', 'Oxford'), 1, 0)` Moreover, it will easier to answer your question if you provide a reproducible example. see [here] ( https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for how to make a great R reproducible example – yang Apr 22 '20 at 15:10

1 Answers1

0

mutate and case_when:


# `%notin%` <- Negate(`%in%`)

tax_data%>% mutate(dummy = case_when(
                  localauthority %in% c('Exeter', 'Glasgow', 'Oxford')~ 1,
                  localauthority %notin% c('Exeter', 'Glasgow', 'Oxford')~0
                                      ) 

or use ifelse:


tax_data%>% mutate(dummy = ifelse(localauthority %in% c('Exeter', 'Glasgow', 'Oxford'),1,0))
user12256545
  • 2,755
  • 4
  • 14
  • 28