简体   繁体   中英

Create dummies on R including multiple categories

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.

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)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM