0

I need to create a dummy which takes the value 1 if the original variable is equal to 3,4,5 and 0 otherwhise. the original variables is an index rescaled from 1 to 7. I already tried this code:

mediumcivlib<-(as.numeric(civlib==3,4,5)

but it gives me back a dummy with 1 corrisponding to three but not to four and five.

  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Apr 14 '20 at 15:47
  • 2
    You probably want something more like `civlib %in% c(3,4,5)`. – MrFlick Apr 14 '20 at 15:50
  • Sorry! I have something like: [ 1 2 3 4 5 6 7 3 4 5 2 3 4 ] and i want r to return me a variable with 1 for values 3,4,5 and 0 otherwhise: [0 0 1 1 1 0 0 1 1 1 0 1 1 ] – CamillaPanel96 Apr 14 '20 at 15:58

1 Answers1

0

The %in% operator checks whether each number in civlib can be found in the second vector of numbers - c(3, 4, 5) in this case. Wrapping this in as.numeric() converts the output from a logical (True or False) to a numeric output as you wanted.

civlib <- c(1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 2, 3, 4)
as.numeric(civlib %in% c(3, 4, 5)) 
Jay Achar
  • 1,156
  • 9
  • 16