Why not use if... else instead? Documentation on ifelse says that "ifelse returns a value with the same shape as test" (emphasis mine), so it's working as intended from it's point of view. if... else doesn't have this problem:
library(tidyverse)
a <-
matrix(
1:4
,nrow = 2
,byrow = TRUE
)
a
#> [,1] [,2]
#> [1,] 1 2
#> [2,] 3 4
a %>% as_tibble()
#> # A tibble: 2 x 2
#> V1 V2
#> <int> <int>
#> 1 1 2
#> 2 3 4
convert_tbl <- function(matrix,is_tibble=FALSE){
if(is_tibble)
as_tibble(matrix)
else
matrix
}
convert_tbl(a, is_tibble = TRUE)
#> # A tibble: 2 x 2
#> V1 V2
#> <int> <int>
#> 1 1 2
#> 2 3 4
convert_tbl(a, is_tibble = FALSE)
#> [,1] [,2]
#> [1,] 1 2
#> [2,] 3 4
Created on 2018-11-06 by the reprex package (v0.2.1)
And not connected to your question, but couple of suggestions on coding style:
- It is better to use
TRUE/FALSE, not T/F. Code is read more often than written, so spare some thought to people who will read it later and seeing TRUE/FALSE is simply easier.
-
is_*** usually indicates a predicate, meaning function that itself will return TRUE/FALSE and not something that is TRUE/FALSE to begin with. The way you use it in your function is probably more like tibblify or convert_to_tibble or something like that.