0

I have created some simple functions in R that take data and return variables. I'd appreciate instruction on taking this to another level using the code below as illustration: There's a data frame 'df' which contains variables DOFW, CDFME (there are others, but two will suffice for this example. I'd like to pass to the function the name of the variable and have it build the barplot. Basically I want to create a function that performs the actions from z<- through abline and call that function for each variable. Thank you.

df<-data.frame(y.train,x.train) z<-ddply(df,~DOFW,summarise,median=median(PCTCHG)) row.names(z)<-z$DOFW z$DOFW<-NULL barplot(t(as.matrix(z)),main="Median Return by DOFW",xlab="DOFW") abline(h=median(y.train)) z<-ddply(df,~CDFME,summarise,median=median(PCTCHG)) row.names(z)<-z$CDFME z$CDFME<-NULL barplot(t(as.matrix(z)),main="Median Return by CDFME",xlab="CDFME") abline(h=median(y.train)) 
1
  • The short answer is that if you want a column name to be a variable, you'll need to use [ instead of $ and adjust your ddply calls to not use a formula or to build the correct formula with paste and expression. The long answer is to read part of Hadley's Advanced R book, paying special attention to the "Non-Standard Evaluation in Subset" section. Commented Jul 11, 2014 at 20:51

1 Answer 1

1

Actually you don't really need non-standard evaluation since ddply allows you to pass a string for the variable name rather than a formula. Here's how you could do that.

#sample data dd<-data.frame(a=rep(1:5, 2), b=2:11, c=runif(10)) #define function library(plyr) myplot<-function(coln) { z<-ddply(dd, coln, summarise, median=median(c)) barplot(z[,2], main=paste("Median Return By", coln)) abline(h=median(dd$c)) } #make plots myplot("a") myplot("b") 

and the easiest way to get the names of the columns as a character vector is names(dd).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.