dplyr::filter changing column type to logical when returning 0-row data.frame.

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"

Created on 2020-09-28 by the reprex package (v0.3.0)

The function class prints the vector of names of classes an object inherits from

df_example <- data.frame(a = c("1","2","3"), b = c("0","0","0"))
class(df_example)
#> [1] "data.frame"
apply(df_example, 2, class) -> result1
class(result1)
#> [1] "character"
df_filtered <- dplyr::filter(df_example, a == "0")
class(df_filtered)
#> [1] "data.frame"
apply(df_filtered, 2, class) -> result2
class(result2)
#> [1] "character"
df_cast_directly <- apply(df_filtered,2, as.character)
class(df_cast_directly)
#> [1] "character"
df_cast_directly2 <- dplyr::mutate_all(df_filtered, as.character)
str(df_cast_directly2)
#> 'data.frame':    0 obs. of  2 variables:
#>  $ a: chr 
#>  $ b: chr
apply(df_cast_directly2, 2, class) -> result3
str(result3)
#>  Named chr [1:2] "logical" "logical"
#>  - attr(*, "names")= chr [1:2] "a" "b"
unclass(result3)
#>         a         b 
#> "logical" "logical"

Created on 2020-09-28 by the reprex package (v0.3.0.9001)

The return object for the last case is a vector of literals, not types

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.