是否有一种简单的方法可以将字符/数字转换为1并将NAs转换为0列?这里是一些示例数据(我要上应用此[3:4]):R:如何将字符/数字变成1和NAs为0?
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")
我预期的结果是:
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
任何建议?谢谢
像'ifelse(is.na(DF [,3:4]),0,1)'? – etienne
或'df [3:4] < - +(!is.na(df [3:4]))' –
@DavidArenburg对于代码golf shenanigans:'1L-is.na(df [3:4])' – Frank