0

I am trying to conditionally assign a tibble to a variable based on a test but I get a list consisting of only one of the columns instead of a tibble when I use ifelse. I know that I can use a regular if ... else statement to do it but I was wondering what causes the behaviour of ifelse

> library(tibble)
> 
> a<- tibble(a =1 , b = 1:3)
> b<- tibble(c =1 , d = 1:3)
> 
> c <- a
> c
# A tibble: 3 x 2
      a     b
  <dbl> <int>
1     1     1
2     1     2
3     1     3
> 
> # INCORRECT
> d <- ifelse(TRUE,a, b)
> d
[[1]]
[1] 1 1 1

> 
> 
> 
> # CORRECT
> if(TRUE){
+   a
+ } else {
+   b
+ }
# A tibble: 3 x 2
      a     b
  <dbl> <int>
1     1     1
2     1     2
3     1     3
Jrakru56
  • 1,211
  • 9
  • 16
  • 1
    See `?ifelse`: "ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE." here, `test` is `TRUE`, so you get a length one result. – Calum You Oct 28 '18 at 00:05
  • 1
    i.e. use `ifelse` for vectorised comparisons, not for regular loops – Calum You Oct 28 '18 at 00:05

0 Answers0