0

Let's say I have a data frame, df, that looks like:

A    B    C   
ABC  DEF  3.1
DEF  GHI  4.0
GHI  JKL  4.5
BXY  JDN  3.3

I want to insert into a new column, D, values (let's say Blue, Red, Green) if A, B, C meet certain criteria.

Something like this:

A    B    C    D 
ABC  DEF  3.1  Blue
DEF  GHI  4.0  Red
GHI  JKL  4.5  Green
BXY  JDN  3.3  Blue

So for example, if the character "B" is present in column A, "D" is present in column B, and C < 3.5, then insert "Blue" in a new column, D. All three criteria need to be met.

This is very similar to a previous question I found: If Column Contains String then enter value for that row which I've tried to modify without success.

I would appreciate any help. Thanks.

1 Answers1

1

If you have lot of conditions to check case_when would be helpful.

library(dplyr)
df %>%
  mutate(D = case_when(grepl('B', A) & grepl('D', B) & C < 3.5 ~ 'Blue', 
                       ...more..condition ~ 'another_value'))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213