2014-02-20 53 views
2

我的數據框有很多列。我希望在許多這些列上執行單獨但類似的xyplot()調用,而無需複製冗長的xyplot()調用。我試過編寫一個函數來做到這一點,但是lattice似乎並不接受文本參數作爲條件變量。複製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) 

謝謝!
布萊恩

回答

3

您可以創建這樣的公式:

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

然後你CAL它:

xyFun("x","ts")