Making a new cloumn in R

Viewed 36

I want to make a new column in r data frame. I want to put in this column values from other column as this example :

ID  column1 column2 
1    C       C
2    B       C
3    A       A
4    C       B

The new column should have any C available in the 2 columns and its value should be present like this :

ID  column1 column2  new column
1    C       C        Present
2    B       C        Present 
3    A       A        Absent
4    C       B        Present

becuse I want the C only from the columns Can you please help me?

2 Answers

We could use ifelse with | operator:

library(dplyr)
df %>% 
    mutate(`new column`= ifelse(column1 == "C" | column2 == "C", "Present", "Absent"))

Output:

  ID column1 column2 new column
1  1       C       C    Present
2  2       B       C    Present
3  3       A       A     Absent
4  4       C       B    Present

This could also be used in base R:

DF$new_column <- Map(function(x, y) c("Absent", "Present")[any("C" %in% c(x, y)) + 1], 
                     DF$column1, DF$column2)
DF

  ID column1 column2 new_column
1  1       C       C    Present
2  2       B       C    Present
3  3       A       A     Absent
4  4       C       B    Present
Related