是否有一種簡單的方法可以將字符/數字轉換爲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