使用基于条件的值创建一个新列

时间:2020-06-26 11:39:39

标签: r if-statement conditional-statements

我需要创建一列,其值基于第三列。示例:

df <- data.frame(antibodies = c("positive","positive","positive","positive",
                            "negative","negative","negative","negative",
                            "negative","positive","positive","negative"),
             AA = c(123, 345, 7567, 234, 8679, 890, 
                    812, 435345, 567, 568, 786, 678),
             stringsAsFactors = F)

我想创建一个名为df$BB的新列,为此列,我需要满足以下两个条件:

  • 如果抗体呈阳性,则BB = AA + 2
  • 如果抗体阴性,则BB == AA

我怎么用R表达这个?

谢谢!

4 个答案:

答案 0 :(得分:4)

这是尝试:

# Base R
df$BB <- ifelse(df$antibodies == "positive", df$AA + 2, df$AA)

# Dplyr
library(dplyr)
df <- df %>% 
  mutate(BB = if_else(antibodies == "positive", AA + 2, AA))

答案 1 :(得分:2)

使用within

df <- within(df, {
  BB <- AA
  BB[antibodies == "positive"] <- BB + 2
})
df
#    antibodies     AA     BB
# 1    positive    123    125
# 2    positive    345    347
# 3    positive   7567   7569
# 4    positive    234    236
# 5    negative   8679   8679
# 6    negative    890    890
# 7    negative    812    812
# 8    negative 435345 435345
# 9    negative    567    567
# 10   positive    568    570
# 11   positive    786    788
# 12   negative    678    678

答案 2 :(得分:2)

使用base R的{​​{1}}函数:

ifelse

或与df$BB <- ifelse(df$antibodies=="positive", df$AA + 2, df$AA)

组合
with

返回

df$BB <- with(df, ifelse(antibodies=="positive", AA + 2, AA))

另一个解决方案可能是

   antibodies     AA     BB
1    positive    123    125
2    positive    345    347
3    positive   7567   7569
4    positive    234    236
5    negative   8679   8679
6    negative    890    890
7    negative    812    812
8    negative 435345 435345
9    negative    567    567
10   positive    568    570
11   positive    786    788
12   negative    678    678

答案 3 :(得分:1)

这是该问题的数据表解决方案。

library(data.table)

setDT(df)
df[, BB := ifelse(antibodies == "positive", AA + 2, AA)]