문제

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")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top