I am facing an error with ggplot2 faceting and dplyr group_by when using a data frame with a date variable. This error only occurs if I first convert the date variable, then melt the data frame. If I do the opposite, the variable appears to be exactly the same, but won't give error. An example:
#base df
df <- data.frame(
id = c("A", "B", "C"),
date1 = c("12/Sep/2010", "13/Mar/2011", "05/Jan/2010"),
date2 = c("13/Sep/2010", "14/Mar/2011", "06/Jan/2010"),
value1 = 1:3,
value2 = 4:6
)
df
id date1 date2 value1 value2
1 A 12/Sep/2010 13/Sep/2010 1 4
2 B 13/Mar/2011 14/Mar/2011 2 5
3 C 05/Jan/2010 06/Jan/2010 3 6
I will show the example with mutate, but using df$date <- as.Date(df$date), gives the same error. I'm sorry or the ugly and inefficient code to tidy my data (suggestions appreciated :-) ).
#mutate first
df_muta <- df %>% mutate_each(funs(as.Date(., format = "%d/%b/%Y")), c(starts_with("date")))
df_muta <- data.frame(
id = melt(df_muta, id.vars = c("id"), measure.vars = c("date1", "date2"))[[1]],
date = melt(df_muta, id.vars = c("id"), measure.vars = c("date1", "date2"))[[3]],
value = melt(df_muta, id.vars = c("id"), measure.vars = c("value1", "value2"))[[3]])
str(df_muta)
'data.frame': 6 obs. of 3 variables:
$ id : Factor w/ 3 levels "A","B","C": 1 2 3 1 2 3
$ date : Date, format: "2010-09-12" "2011-03-13" "2010-01-05" ...
$ value: int 1 2 3 4 5 6
p <- ggplot(df_muta, aes(x = date, y = value)) + geom_point()
I wanted to post the plot, but don't have 10 reputation yet to do it. The single plot above is ok, with dates on the x axis. If I try to facet, the x axis will be converted to numeric.
p + facet_wrap( ~ id)
And if I try to used dplyr group_by it will error too.
df_muta %>% group_by(id)
Error: column 'date' has unsupported type
So I tried first melting, then converting the date.
df_melt <- data.frame(
id = melt(df, id.vars = c("id"), measure.vars = c("date1", "date2"))[[1]],
date = melt(df, id.vars = c("id"), measure.vars = c("date1", "date2"))[[3]],
value = melt(df, id.vars = c("id"), measure.vars = c("value1", "value2"))[[3]])
df_melt <- df_melt %>% mutate(date = as.Date(date, format = "%d/%b/%Y"))
str(df_melt)
'data.frame': 6 obs. of 3 variables:
$ id : Factor w/ 3 levels "A","B","C": 1 2 3 1 2 3
$ date : Date, format: "2010-09-12" "2011-03-13" "2010-01-05" ...
$ value: int 1 2 3 4 5 6
The structure and values of both data frames appear to be exactly the same, but this last one won't give any errors with the facet plot axis or group_by. Is it a bug? Where is the difference between the date objects?
Thanks!