[R] Comparing "transform" to "with"

Muenchen, Robert A (Bob) muenchen at utk.edu
Sat Sep 1 15:23:30 CEST 2007


Hi All,

I've been successfully using the with function for analyses and the
transform function for multiple transformations. Then I thought, why not
use "with" for both? I ran into problems & couldn't figure them out from
help files or books. So I created a simplified version of what I'm
doing:

rm( list=ls() )
x1<-c(1,3,3)
x2<-c(3,2,1)
x3<-c(2,5,2)
x4<-c(5,6,9)
myDF<-data.frame(x1,x2,x3,x4)
rm(x1,x2,x3,x4)
ls()
myDF

This creates two new variables just fine"

transform(myDF,
  sum1=x1+x2,
  sum2=x3+x4
)

This next code does not see sum1, so it appears that "transform" cannot
see the variables that it creates. Would I need to transform new
variables in a second pass?

transform(myDF,
  sum1=x1+x2,
  sum2=x3+x4,
  total=sum1+sum2
)

Next I'm trying the same thing using "with". It doesn't not work but
also does not generate error messages, giving me the impression that I'm
doing something truly idiotic:

with(myDF, {
  sum1<-x1+x2
  sum2<-x3+x4
  total <- sum1+sum2
} )
myDF
ls()

Then I thought, perhaps one of the advantages of "transform" is that it
works on the left side of the equation without using a longer name like
myDF$sum1. "with" probably doesn't do that, so I use the longer form
below. It also does not work and generates no error messages. 

# Try it again, writing vars to myDF explicitly.
# It generates no errors, and no results.
with(myDF, {
  myDF$sum1<-x1+x2
  myDF$sum2<-x3+x4
  myDF$total <- myDF$sum1+myDF$sum2
} )
myDF
ls()

I would appreciate some advice about the relative roles of these two
functions & why my attempts with "with" have failed.

Thanks!
Bob

=========================================================
Bob Muenchen (pronounced Min'-chen), Manager 
Statistical Consulting Center
U of TN Office of Information Technology
200 Stokely Management Center, Knoxville, TN 37996-0520
Voice: (865) 974-5230 
FAX: (865) 974-4810
Email: muenchen at utk.edu
Web: http://oit.utk.edu/scc, 
News: http://listserv.utk.edu/archives/statnews.html



More information about the R-help mailing list