在运动图中使用有序因子作为timevar [英] Using a ordered factor as timevar in Motion Chart
问题描述
我有一些这样的数据:
time var1 var2 idvar
1 Q1 1 4 A
2 Q1 2 3 B
3 Q2 3 2 A
4 Q2 4 1 B
我需要使用每个四分之一(Q1
和Q2
)作为时间变量来创建MotionChart
.我试图使df$time
成为有序因子,但是由于timevar
需要采用数字或日期格式,因此它仍然给我一个错误.有什么解决方法吗?我的实际数据以YYYYQn
格式跨越了几年,并且每年的所有四个季度都是我不想更改的.
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")
输出错误:
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
推荐答案
您为什么转换为factor
?文档说timevar
参数不能处理因数.当且仅当它们采用特殊格式(例如:2010Q1
)时,它才能处理character
.当然,它可以处理Date
.
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
.
这是我的解决方案:
我只是创建了一个带有转换的新列,在其中将年份(您必须知道,否则您可以使用代理)粘贴到所有Q1
,Q2
等上.通过使用回收规则,这并不难想想,这只是一个小例子.
之后,我将该列转换为character
.
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)
df1
会像这样:
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")
生成此图(使用plot(g)
):
produces this plot (with plot(g)
):
这篇关于在运动图中使用有序因子作为timevar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!