r - 尝试在 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
解决方案
你可以试试下面的代码
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"))
推荐阅读
- reactjs - 我们如何通过 highcharts-react-official 包显示加载
- vue.js - 如何在 VueCli 中构建没有文件名哈希
- junit - JUnit 使用双精度的 assertEquals
- python - altair 中的分组条形图
- javascript - 覆盖 Ajax 成功
- c - 更好的方式来分配内存以获得灵活性和处理
- python - 按元素对 2d numpy 数组求和
- html - 需要更改下拉菜单容器对齐方式
- tensorflow - Matterport Mask R-CNN - 较大图像的不可预测的损失值和奇怪的检测结果
- excel - 使用 VBA 到 oracle 数据库捕获错误的数据库凭据