[R] abbreviate function using 'with'

Rolf Turner r.turner at auckland.ac.nz
Thu Feb 13 21:06:48 CET 2014

On 14/02/14 10:46, e-letter wrote:

> Readers,
> A csv file was created:
> column1,column2,column3,column4
> 1,10,3,2
> 2,20,6,4
> 3,30,12,16
> 4,40,24,256
> The csv was imported:
> testcsv<-read.csv('/path/to/test.csv')
> testsum<-testcsv[2,2]+testcsv[2,3]+testcsv[2,4]
> What is the correct syntax to abbreviate the following command using
> the function 'with', to avoid repetitive use of the declaration
> 'testcsv'? Tried the following, but received the error shown:
> with(testcsv,testsum<-[2,2]+[2,3]+[2,4])
> Error: unexpected '[' in "with(testcsv,testsum<-["
> and:
> with(testcsv,{testsum<-[2,2]+[2,3]+[2,4]})
> Error: unexpected '[' in "with(testcsv,{testsum<-["

What you've written is simply not (anything like!) R syntax.  You should 
learn to speak R if you are going to use R.

In this particular instance

	testsum <- sum(testcsv[2,2:4])

should give what you want.   The use of with() is uncalled for in this
context.  The with() function allows you to refer to (e.g.) columns of
a data frame by name, as if these columns were objects in your workspace 
("global environment").  That is *not* what you are doing, or need to do 


Rolf Turner

P. S.:  Please read fortune("people who don't exist") and change your 
modus operandi.

R. T.

More information about the R-help mailing list