Hi,
I have a tmpFlag logical outside of the tribble ttmp.
Could somebody explain why my first version of ifelse command gives a wrong output and the second version resolves it by adding rowwise()? The third version is correct as expected.
Thanks.
Ha
library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 4.1.3
#> Warning: package 'ggplot2' was built under R version 4.1.3
#> Warning: package 'tibble' was built under R version 4.1.3
#> Warning: package 'tidyr' was built under R version 4.1.2
#> Warning: package 'readr' was built under R version 4.1.2
#> Warning: package 'purrr' was built under R version 4.1.2
#> Warning: package 'dplyr' was built under R version 4.1.3
#> Warning: package 'stringr' was built under R version 4.1.2
#> Warning: package 'forcats' was built under R version 4.1.2
#tidyverse: version 1.3.1
tmpFlag = FALSE
ttmp = tibble(x=c(1:4, NA))
# Wrong answer
ttmp %>%
mutate(y=ifelse(tmpFlag, NA, x))
#> # A tibble: 5 x 2
#> x y
#> <int> <int>
#> 1 1 1
#> 2 2 1
#> 3 3 1
#> 4 4 1
#> 5 NA 1
# Correct answer by adding rowwise()
ttmp %>%
rowwise() %>%
mutate(y=ifelse(tmpFlag, NA, x))
#> # A tibble: 5 x 2
#> # Rowwise:
#> x y
#> <int> <int>
#> 1 1 1
#> 2 2 2
#> 3 3 3
#> 4 4 4
#> 5 NA NA
# This has a correct output as expected
ttmp %>%
mutate(Flag=tmpFlag,
y=ifelse(Flag, NA, x))
#> # A tibble: 5 x 3
#> x Flag y
#> <int> <lgl> <int>
#> 1 1 FALSE 1
#> 2 2 FALSE 2
#> 3 3 FALSE 3
#> 4 4 FALSE 4
#> 5 NA FALSE NA
Created on 2023-03-14 by the reprex package (v2.0.1)