[R] variable name substitution

Duncan Murdoch murdoch at stats.uwo.ca
Mon Jan 18 16:26:18 CET 2010


On 18/01/2010 9:02 AM, Ivan Calandra wrote:
> Hi everybody!
>
> I'm trying to write a script to plot a histogram, a boxplot and a 
> qq-plot (under Windows XP, R2.10 if it matters)
>
> What I want to do: define the variables (x and y) to be used at the very 
> beginning, so that I don't have to change all occurrences in the script 
> when I want to plot a different variable.
>
> The dataset is called "ssfa". TO_POS is a categorical variable 
> containing the tooth position for each sample. Asfc is a numerical 
> variable. In my dataset, I have more variables but it wouldn't change; I 
> want to plot one numeric vs one category. Do I need to supply some data? 
> I don't think it's really necessary but let me know if you would like to.
>
> The code of what I do up to now:
> ---
> x <- ssfa$TO_POS
> y <- ssfa$Asfc
> hist(y, main="Histogram of Asfc", xlab="Asfc")
> boxplot(y~x, main="Boxplot of Asfc by TO_POS", xlab="TO_POS", ylab="Asfc")
> ---
>
> I would like something like: hist(y, main="Histogram of y", xlab="y") 
> but that will add "Asfc" where I write "y".
> And the same for boxplot(y~x, main="Boxplot of y by x", xlab="x", ylab="y")
> I thought about something like:
> ---
> cat <- "TO_POS"
> num <- "Asfc"
> x <- paste("ssfa$", "TO_POS", sep="")
> y <- paste("ssfa$", "Asfc", sep="")
> hist(y, main=paste("Histogram of ", cat, sep=""), xlab=num)
> ---
> but it doesn't work since y is a string. I don't know how to get the 
> syntax correctly. I am on the right path at least?!
>   

I think you're on the wrong path.  You want to write a function, and 
pass either x and y as arguments, or pass a formula containing both (the 
former is easier).  For example,

twoplots <- function(x, y) {
  ylab <- deparse(substitute(y))  # get the expression passed as y
  xlab <- deparse(substitute(x))  # get the expression passed as x
  hist(y, main=paste("Histogram of ", ylab), xlab=ylab)
  boxplot(y ~ x,  main=paste("Boxplot of", ylab, "by", xlab), xlab=xlab, 
ylab=ylab)
}

Then

with(ssfa, twoplots(TO_POS, Asfc))

will give you your plots.

Duncan Murdoch



More information about the R-help mailing list