将条件变量传递给格子函数中的xyplot(组)

时间:2014-02-21 19:57:22

标签: r function formula lattice

Passing conditioning variables to xyplot in a function in lattice上构建,我想知道如何通过函数调用传递“组”。使用公式()似乎不起作用,就像它对其他条件变量一样。

df=data.frame(ts=c(1:100), x=runif(100), y=3, g=c("A","B"))

# This is the clunky approach I want to avoid
tp <- xyplot(x~ts, df, groups=g) # imagine 10 lines of detailed parameters
plot(tp)
tp <- xyplot(y~ts, df, groups=g)
plot(tp)

# This is my attempt at writing a function to simplify the code (it does not work)
xyFun <- function(varName, tsName, DF=df, groupName){
  form <- formula(paste(tsName,varName,sep="~"))
  xyplot(form, DF, groups=formula(groupName))
}

xyFun("x","ts",df,"g") # this does not work
# Error in formula.default(DF[, groupName]) : invalid formula 
xyFun("y","ts",df,"g") 

有什么想法吗?谢谢!
布赖恩

1 个答案:

答案 0 :(得分:1)

你可以简单地尝试使用&#34; ...&#34;以这种方式论证

xyFun <- function(varName, tsName, DF=df, ... ){
  form <- formula(paste(tsName,varName,sep="~"))
  xyplot(form, DF,...)

}

然后启动函数

xyFun("x", "ts", groups= g)