简体   繁体   English

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

[英]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.

相关问题 如何用1和0覆盖R中的一列字符? - How do I overwrite a column of characters in R with 1s and 0s? 在矩阵中将NA的矩阵转换为0并将连续变量转换为1 - converting a matrix of NAs to 0s and continous variables to 1s in a matrix 如何将分类变量二分为具有 1 和 0 的新变量但保持 NA? - How to dichotomize categorical variables into a new variable with 1s and 0s but maintain NAs? 在r中的多列中计算0s 1s和2s - Counting 0s 1s and 2s in multiple column in r r 生成具有随机 1 和 0 的列,有限制 - r generate a column with random 1s and 0s with restrictions 从 r 中的数据集中删除尾随的 0 和 1 - Removing trailing 0s and 1s from a dataset in r 如何在R中创建一个填充了1和0的表,以显示来自另一个表的值的存在? - How to create a table in R populated with 1s and 0s to show presence of values from another table? 如何分析R中数据集中信号(1s和0s)的连续持久性? - How can I analyze the consecutive persistence of signals (1s and 0s) in dataset in R? 如果行中的变量在 R 中匹配或不匹配,如何将 1 和 0 分配给列 - How to assign 1s and 0s to columns if variable in row matches or not match in R 如何根据来自其他几个文件的值来创建R中的表1和0 - How to create a table in R with 1s and 0s based on the presence of values from several other files
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM