0
votes

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!

1
Is as.numberic() a typo? Does your code work if you change it to as.numeric()? - jared_mamrot
Try with if_else(Rg_SE * 2 > abs(as.numeric(Rg)), NA_real_, Rg)). BTW: Looks like Rg is already a numeric. So as.numeric is probably not necessary. - stefan
try searching help for a correct way of writing syntaxes for both. ?if_else or ?case_when - AnilGoyal

1 Answers

2
votes

Here is one potential solution:

library(tidyverse)
df <- read.table(text = "               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", header = TRUE)

df %>% 
  mutate(Rg = ifelse((Rg_SE*2) > abs(as.numeric(as.character(Rg))), NA, Rg))
#   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