首页 > 解决方案 > 尝试在 R 中修复二进制文件时出现代码问题

问题描述

我试图计算答案<=2的个人数量。当我这样做时length(which(healthProb$healthProblem <=2))

我得到了答案 253。当我将它们转换为 <=2 为 1 的二进制文件时,我得到的答案是零个人被编码为 1。如何修复我的二进制代码?

二进制代码:

healthProb <- data.frame(healthProb, binary = 0)
rows_under_2 <- which(healthProb$healthProblem <= 2)
dat4[rows_under_2, 3] <- 1
table(healthProb$binary)

我的数据框负责人:

Organisation healthProblem binary
1       xxxx             1      0
2       xxxx             3      0
3       xxxx             5      0
4       xxxx             3      0
5       xxxx             4      0
6       xxxx             4      0

标签: r

解决方案


你可以试试下面的代码

df <- within(df,binary <- ifelse(healthProblem<=2,1,0))

或更快的方法(感谢@PoGibas)

df <- within(df,binary <- as.numeric(healthProblem<=2))

这使

> df
  Organisation healthProblem binary
1         xxxx             1      1
2         xxxx             3      0
3         xxxx             5      0
4         xxxx             3      0
5         xxxx             4      0
6         xxxx             4      0

数据

df<-structure(list(Organisation = structure(c(1L, 1L, 1L, 1L, 1L, 
1L), .Label = "xxxx", class = "factor"), healthProblem = c(1L, 
3L, 5L, 3L, 4L, 4L), binary = c(0L, 0L, 0L, 0L, 0L, 0L)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

推荐阅读