vcat
vcat

Reputation: 263

two conditions in one column and another condition in another column to make a new column in R

    df$A(12, 12, 17, 17, 17, 99, 99, 56, 56, 56, 13, 13, 13, 89, 89, 89)
df$C(Aplus, Bplus, Aplus, A,  Aplus, Dplus, A,  A,  Cminus, Dplus, Aplus, A,  Dplus, Aminus, Aplus, Dplus)
df$D(mt, mt, mt, wt, wt, mt, mt, wt, wt, wt, mt, wt, wt, wt, mt, wt)

I would like to create a new column E on the bottom in which the following are true.

WT Aplus equal to mt and Bplus

SS A equal to wt, Cminus equal to wt, Dplus equal to wt

HH Aplus equal to mt or Dplus

df$E(WT, WT, NA, NA, NA, HH, NA, SS, SS, SS, HH, NA, HH, NA, HH, HH)


df1 <- df %>% mutate(E = ifelse(D %in% c("A+" & "B+") & E == "mt", "WT"))
df1 <- df %>% mutate(E = ifelse(D %in% c("A" & "C-" & "D+") == "wt", "SS"))
df1 <- df %>% mutate(E = ifelse(D %in% c("A+" & "D+"), "HH"))

Any help would be greatly appreciated as I am unable to get the df$E output stated above. Instead for the first line of code that I run to implement WT Aplus equal to mt and Bplus, I get this output of 5 WT instead of 2 WT

df$E(WT, WT, WT, NA, NA, NA, NA, NA, NA, NA, WT, NA, NA, NA, WT, NA)

Upvotes: 0

Views: 48

Answers (1)

akrun
akrun

Reputation: 887118

We can use case_when for multiple conditions

library(dplyr)
df %>%
    mutate(E = case_when(D %in%  c("A+", "B+") &  E == 'mt' ~ 'WT',
                         D %in% c("A", 'C-', 'D+') == 'wt' ~ 'SS',
                         D %in% c('A+', 'D+') ~ "HH"))

Upvotes: 1

Related Questions