R:如何将字符/数字转换为1并将NA转换为0?

时间:2015-12-02 13:17:11

标签: r

是否有一种简单的方法可以将字符/数字转换为1,将NAs转换为0作为列?这里有一些示例数据(我想在[,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")

我的预期结果是:

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

有什么建议吗?谢谢

1 个答案:

答案 0 :(得分:3)

我将数据框命名为d

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

对于许多专栏更好:

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]))

(来自etienne和David的评论中的代码)