[R] Please help with a basic function

Don MacQueen macq at llnl.gov
Fri Dec 11 22:18:54 CET 2009


At 8:19 AM -0600 12/11/09, Mark Na wrote:
>Hello,
>
>I am learning how to use functions, but I'm running into a roadblock.
>
>I would like my function to do two things: 1) convert an object to a
>dataframe, 2) and then subset the dataframe. Both of these commands work
>fine outside the function, but I would like to wrap them in a function so I
>can apply the code iteratively to many such objects.
>
>Here's what I wrote, but it doesn't work:
>
>convert<-function(d) {
>  d<-data.frame(d); #convert object to dataframe
>  d<-subset(d,select=c(time,coords.x1,coords.x2)) #select some columns
>}
>convert(data) #the problem is that "data" is the same as it was before
>running the function


Objects (variables, data frames, etc) inside a function are in a 
different environment than those outside the function, and changes 
inside do not affect the outside unless you explicitly make it 
happen. In other words, you changed d inside the function, but did 
nothing to cause it to change data outside the function.

Change your function like this

convert<-function(d) {
  d<-data.frame(d); #convert object to dataframe
   ## no need to assign to d in the next line
  subset(d,select=c(time,coords.x1,coords.x2)) #select some columns
}

Then do:

   data <- convert(data)


Or the function could be

convert<-function(d) {
  d<-data.frame(d); #convert object to dataframe
  d <-  subset(d,select=c(time,coords.x1,coords.x2)) #select some columns
  d
}


The use of return() as suggested in another response is unnecessary. 
Functions return the value of their last expression, though possibly 
invisibly if the last expression is an assignment. For example;

  ick <- function(x) {
   x^2
  }

>  ick(4)
[1] 16
>  ick(3)
[1] 9


  ick <- function(x) {
   y <- x^2
  }

>  foo <- ick(4)
>  foo
[1] 16

The invisible return as in the second case is something I hadn't 
noticed before, and may deserve some reading of documentation.

-Don



>
>The objects being processed through my function are SpatialPointsDataFrames
>but I'm quite sure that's not my problem, as I can process these outside of
>the function (using the above code) ... it's when I try to wrap the code in
>a function that it doesn't work.
>
>Thanks, Mark
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list
>https://*stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide http://*www.*R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.


-- 
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
925-423-1062




More information about the R-help mailing list