尝试将其修复为R中的二进制代码时出现问题

问题描述 投票:0回答:1

我试图计算答案<= 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
1个回答
0
投票

您可以尝试以下代码

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

DATA

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"))
© www.soinside.com 2019 - 2024. All rights reserved.