将条件变量传递给格中函数中的xyplot [英] Passing conditioning variables to xyplot in a function in lattice
本文介绍了将条件变量传递给格中函数中的xyplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ $ p $
df = data.frame(ts = c(1:100),x = runif(100),y = 3, z = rnorm(100))
#这是我想要避免的笨重方法
tp < - xyplot(x〜ts,df)#想象〜10行xyplot调整参数
plot(tp)
tp < - xyplot(y〜ts,df)
plot(tp)
tp < - xyplot(z〜ts,df)
plot(tp)
#这是我在编写函数以简化代码的尝试(它不起作用)
xyFun< - function(varName,tsName,DF){
TP< -xyplot(varName〜tsName,DF)
plot(TP)
}
xyFun(x,ts,df)#这些不起作用因为调节变量是文本
xyFun(y,ts,df)
xyFun(z,ts,df)
pre> 谢谢!
Bryan
解决方案
你可以像这样创建公式:
xyFun< - function(varName,tsName,DF = df){
form< - 公式(paste(tsName,varName,sep =〜))
xyplot(form,DF)
}
然后你确定它:
xyFun(x,ts)
My dataframe has many columns. I wish to perform separate but similar xyplot() calls on many of these columns without endlessly copying the lengthy xyplot() call. I've tried writing a function to do this, but lattice does not seem to accept text arguments as conditioning variables. Duplicating xyplot calls are making my code unwieldy. Any ideas?
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)
Thanks!
Bryan
解决方案
You can create the formula like this :
xyFun <- function(varName, tsName, DF=df){
form <- formula(paste(tsName,varName,sep="~"))
xyplot(form, DF)
}
Then you cal it :
xyFun("x","ts")
这篇关于将条件变量传递给格中函数中的xyplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文