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.
Below is an example data.frame.
When I spread this df by the "var" column, call like
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:
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.