[英]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? 有没有一种简单的方法可以将字符/数字转换为1,将NA转换为0的列? Here some example data (I want to apply this on [,3:4]):
这里是一些示例数据(我想在[,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
:
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) (来自etienne和David的评论的代码)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.