Lili
Lili

Reputation: 587

Create a new column with values based on conditions

I would need to create a column with values based on a third column. Example:

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)

I want to create a new column named df$BB, to make this column I want the following 2 conditions:

How can I express this in R?

Thank you!

Upvotes: 0

Views: 100

Answers (4)

ljwharbers
ljwharbers

Reputation: 393

Here a data.table solution for the problem.

library(data.table)

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

Upvotes: 1

Martin Gal
Martin Gal

Reputation: 16998

Using base R's ifelse-function:

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

or combined with with

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

returns

   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

Another solution could be

df$BB <- as.numeric(df$antibodies == "positive") * 2 + df$AA

Upvotes: 2

jay.sf
jay.sf

Reputation: 73602

Using 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

Upvotes: 2

Chris
Chris

Reputation: 296

Here is an attempt:

# 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))

Upvotes: 4

Related Questions