简体   繁体   中英

R: How to turn characters/numeric into 1s and NAs into 0s?

Is there an easy way to turn characters/numeric into 1 and NAs into 0 for columns? Here some example data (I want to apply this on [,3:4]):

structure(list(Item.Code = c(176L, 187L, 191L, 201L, 217L, 220L
), Item.x = structure(c(1L, 6L, 4L, 5L, 2L, 3L), .Label = c("Beans, dry", 
"Cashew nuts, with shell", "Chestnut", "Chick peas", "Lentils", 
"Peas, dry"), class = "factor"), Item.y = c("Beans, dry", "Peas, dry", 
"Chick peas", "Lentils", NA, "Chestnut"), WFcode = structure(c(1L, 
2L, 3L, 4L, NA, 5L), .Label = c("176", "187", "191", "201", "220"
), class = "factor")), .Names = c("Item.Code", "Item.x", "Item.y", 
"WFcode"), row.names = c(NA, 6L), class = "data.frame")

My expected result is:

Item.Code            Item.x Item.y WFcode
176              Beans, dry      1      1
187               Peas, dry      1      1
191              Chick peas      1      1
201                 Lentils      1      1
217 Cashew nuts, with shell      0      0
220                Chestnut      1      1

Any suggestions?, thanks

I named the dataframe d :

d$Item.y <- as.integer(!is.na(d$Item.y))
d$Item.WFcode <- as.integer(!is.na(d$Item.WFcode))

For many columns better:

df[,3:4] <- ifelse(is.na(df[,3:4]), 0, 1) # or
df[3:4] <- +(!is.na(df[3:4])) # '+' converts to integer or
df[3:4] <- as.integer(!is.na(df[3:4]))

(code from the comments from etienne and David)

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