mercredi 26 mai 2021

Combine mutate with conditional statement using a formula in r

I am trying to mutate my dataframe based on a condition that is containing a formula. I was thinking to use mutate in combination with if_else or case_when (not sure what the exact difference is between the two), but it's not working for me.

My data frame looks like this:

> dat.example
               t1             t2      Rg Rg_SE
1              WT            Fat  0.6818 0.0962
2              WT          FatPC  0.1853 0.1354
3              WT            DTD -0.1684 0.1232
4             Fat        DefCode      NA 0.1608

What I would like to do is change values in the column Rg to 'NA' if the value in column Rg_SE times 2 is bigger than the absolute value in column Rg. NA values in column Rg should be ignored. So, output should look like this:

> output
               t1             t2      Rg Rg_SE
1              WT            Fat  0.6818 0.0962
2              WT          FatPC      NA 0.1354
3              WT            DTD      NA 0.1232
4             Fat        DefCode      NA 0.1608

Now I have used this piece of code:

dat.example2 <- dat.example %>% mutate(Rg = if_else(Rg_SE*2 > abs(as.numberic(as.character(Rg))) ~ "NA"))

which is giving me this error message:

Error: Problem with `mutate()` input `Rg`.

x condition must be a logical vector, not a formula object. i Input Rg is if_else(Rg_SE * 2 > abs(as.numberic(as.character(Rg))) ~ "NA").

Does anyone have ideas how to do this? Many thanks!

Aucun commentaire:

Enregistrer un commentaire