我的数据框有很多列。我希望在许多这些列上执行单独但类似的xyplot()调用,而无需无休止地复制冗长的xyplot()调用。我试过写一个函数来做这个,但格子似乎不接受文本参数作为条件变量。复制xyplot调用使我的代码变得笨拙。有任何想法吗?
df=data.frame(ts=c(1:100),x=runif(100),y=3,z=rnorm(100))
# This is the clunky approach I want to avoid
tp <- xyplot(x~ts, df) # imagine ~10 lines of xyplot tweaking parameters
plot(tp)
tp <- xyplot(y~ts, df)
plot(tp)
tp <- xyplot(z~ts, df)
plot(tp)
# This is my attempt at writing a function to simplify the code (it does not work)
xyFun <- function(varName, tsName, DF){
TP<-xyplot(varName~tsName, DF)
plot(TP)
}
xyFun("x","ts",df) # these don't work because conditioning variables are text
xyFun("y","ts",df)
xyFun("z","ts",df)
谢谢!
布赖恩
答案 0 :(得分:3)
您可以像这样创建公式:
xyFun <- function(varName, tsName, DF=df){
form <- formula(paste(tsName,varName,sep="~"))
xyplot(form, DF)
}
然后你来吧:
xyFun("x","ts")