mercredi 20 mai 2020

Strange behevior of ifelse() in R: when are the values evaluated?

I have the following data:

df = data.frame(
  stat = c('mean', 'var'),
  value = c(-9, 10))

Let say I want to take the square of 'value' if 'stat' is "var", and do nothing if not.

df %>% 
  mutate(
   value = ifelse(stat=='var', sqrt(value), value))

I get a warning:

Warning message:
In sqrt(-9) : NaNs produced

Why am I getting the warning? The value sqrt(-9) is not supposed to be computed as 'value' is "mean"

Aucun commentaire:

Enregistrer un commentaire