下面是 gvisMotionChart 的一个小接口函数,除了 idvar 和 timevar 之外,它还允许指定 xvar、yvar、colorvar 和 sizevar 的默认值。它通过简单地更改提供的 data.frame 的列顺序来实现这一点。该函数还将布尔值转换为数字(否则 gvisMotionChart 会引发错误)。由于我的运动图也很方便分析横截面数据,它允许设置timevar=NULL。
# Convenience interface to gvisMotionChart that allows to set default columns
myMotionChart = function(df,idvar=colnames(df)[1],timevar=colnames(df)[2],xvar=colnames(df)[3],yvar=colnames(df)[4], colorvar=colnames(df)[5], sizevar = colnames(df)[6],...) {
library(googleVis)
# Generate a constant variable as column for time if not provided
# Unfortunately the motion plot still shows 1900...
if (is.null(timevar)) {
.TIME.VAR = rep(0,NROW(df))
df = cbind(df,.TIME.VAR)
timevar=".TIME.VAR"
}
# Transform booleans into 0 and 1 since otherwise an error will be thrown
for (i in 1:NCOL(df)) {
if (is.logical(df [,i])[1])
df[,i] = df[,i]*1
}
# Rearrange columns in order to have the desired default values for
# xvar, yvar, colorvar and sizevar
firstcols = c(idvar,timevar,xvar,yvar,colorvar,sizevar)
colorder = c(firstcols, setdiff(colnames(df),firstcols))
df = df[,colorder]
gvisMotionChart(df,idvar=idvar,timevar=timevar,...)
}