Skip to content

spread() with drop = FALSE applied to var column including NA values results an error #254

Description

@ngr-t

Below is an example data.frame.

> (df_with_na <- data.frame(var = factor(c(LETTERS[1:3], NA), LETTERS[1:4]), val = seq(4)))
   var val
1    A   1
2    B   2
3    C   3
4 <NA>   4
> df_with_na$var
[1] A    B    C    <NA>
Levels: A B C D

When I spread this df by the "var" column, call like

> tidyr::spread(df_with_na, var, val)
  A B C <NA>
1 1 2 3    4

In this case, I got an column "" originate from the row that contains NA in "var" column.
Then I added "drop = FALSE" option to keep all levels (including "D"), and got this:

> tidyr::spread(df_with_na, var, val, drop = FALSE)
Error in `colnames<-`(`*tmp*`, value = c("A", "B", "C", "D", "<NA>")) : 
  length of 'dimnames' [2] not equal to array extent

I think this is not an intended behavior and it'd better to return a data.frame with columns for all levels of "var" column and NA.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    reprexneeds a minimal reproducible example

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions