简体   繁体   English

以 R 数据框中的其他列为条件创建新的二进制列

[英]Create new binary column conditional on other column in R data frame

Trying to input a scoring system into R so I can validate it for my data.尝试将评分系统输入到 R 中,以便我可以针对我的数据对其进行验证。

I want to assign a score to set binary outcomes.我想分配一个分数来设置二元结果。

In this case if my patient has heamaglobin (Hb) <8 (yes 1 or no 0).在这种情况下,如果我的患者的血红蛋白 (Hb) <8(是 1 或否 0)。 I want to assign a score of 5 points when haemoglobin (Hb<8) = 1.当血红蛋白 (Hb<8) = 1 时,我想给 5 分。

| Patient number | Hb<8 |
|----------------|------|
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 1 |

How do I create a new coloumn that would read either 0 or 5 depending on the factor in the Hb coloumn?如何根据 Hb 列中的因子创建一个新列,该列将读取 0 或 5?

Many thanks非常感谢

Try this:尝试这个:

df <- data.frame(patient = c(1, 2, 3, 4),
                 hb_smaller_8 = c(0, 1, 0, 1))

df <- df %>% mutate(score = ifelse(hb_smaller_8 == 1, 5, 0))
> df
  patient hb_smaller_8 score
1       1            0    NA
2       2            1     5
3       3            0    NA
4       4            1     5

A simple ifelse statement in base R will do: base R一个简单ifelse语句将执行以下操作:

df$score <- ifelse(df$hb_smaller_8 == 1, 5, NA)

df
  patient hb_smaller_8 score
1       1            0    NA
2       2            1     5
3       3            0    NA
4       4            1     5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM