简体   繁体   中英

R Recode Variable In List

data=data.frame(X=c(1,2,3,4,5,6,7,8,9),
                Y = c(1,0,0,0,1,1,2,2,1))

I have data with column X and wish to recode with this rule: if X equals to 1,5,6,9 then Y equals to 1 but if X equals to 2,3,4 then Y equals to 0 and if X equals to 7,8 then Y equals to 2. I am wondering, how to do this with not using 'if' statements. Maybe on dplyr, data.table for example.

Maybe you can try the code below without if

v1 <- c(1,5,6,9)
v2 <- c(2,3,4)
v3 <- c(7,8)

dfout <- within(data,Y <- 1*(X %in% v1) + 0*(X %in% v2) + 2*(X %in% v3))

such that

> dfout
  X Y
1 1 1
2 2 0
3 3 0
4 4 0
5 5 1
6 6 1
7 7 2
8 8 2
9 9 1

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