When dplyr::filter results in a 0-row data.frame it appears to change all column types to logical.
Is there a way to avoid this? I'd like to preserve the column types despite the 0-rows. I tried a couple ways to recast the column types directly, but neither worked.
Here is a reprex (user dplyr version 1.0.2):
df_example <- data.frame(a = c("1","2","3"), b = c("0","0","0"))
df_example
#> a b
#> 1 1 0
#> 2 2 0
#> 3 3 0
apply(df_example, 2, class)
#> a b
#> "character" "character"
df_filtered <- dplyr::filter(df_example, a == "0")
df_filtered
#> [1] a b
#> <0 rows> (or 0-length row.names)
apply(df_filtered, 2, class)
#> a b
#> "logical" "logical"
df_cast_directly <- apply(df_filtered,2, as.character)
df_cast_directly
#> character(0)
df_cast_directly2 <- dplyr::mutate_all(df_filtered, as.character)
df_cast_directly2
#> [1] a b
#> <0 rows> (or 0-length row.names)
apply(df_cast_directly2, 2, class)
#> a b
#> "logical" "logical"