I have some data like this:
time var1 var2 idvar
1 Q1 1 4 A
2 Q1 2 3 B
3 Q2 3 2 A
4 Q2 4 1 B
I need to make a MotionChart
using each quarter (Q1
and Q2
) as a time var. I have tried to make df$time
an ordered factor, but it still gives me an error as the timevar
needs to be in numeric or date format. Is there any workaround with this? My actual data spans several years and all 4 quarters of each year in the YYYYQn
format, which I would not like to change.
The code I'm using in this example:
library(googleVis)
df = data.frame(time = c("Q1","Q1","Q2","Q2"),var1 = c(1,2,3,4),var2=c(4,3,2,1),idvar=c("A","B","A","B"))
df$time = ordered(df$time)
g = gvisMotionChart(df,timevar="time",idvar="idvar")
The output is an error:
Error : The timevar has to be of numeric or Date format. Currently it is orderedThe timevar has to be of numeric or Date format. Currently it is factor
Why did you converted to factor
? the documentation says that timevar
argument can't handle factor. It can handle character
if and only if they are in a particular format, that is (for example): 2010Q1
. Of course it can handle Date
.
Here is my solution:
I just create a new column with transform where I paste the year (which you have to know, otherwise you could use a proxy) to all the Q1
, Q2
etc. it won't be hard by using recycling rules I think, here is just a little example.
After that I convert that column into character
.
transform(df, time2 = paste(2010, df$time, sep = "")) -> df1
df1$time2 <- as.character(df1$time2)
The df1
will be like that:
df1
time var1 var2 idvar time2
1 Q1 1 4 A 2010Q1
2 Q1 2 3 B 2010Q1
3 Q2 3 2 A 2010Q2
4 Q2 4 1 B 2010Q2
After that you can use your code:
g = gvisMotionChart(df1,timevar="time2",idvar="idvar")