[R] Using a function to consolidate variables

Phil Spector spector at stat.berkeley.edu
Thu Mar 18 20:08:47 CET 2010


David -
    I think what you're looking for is something like this:

> mydat = data.frame(a=c(1,2,3),b=c(5,1,4))
> consolidate.fun = function(data,var1,var2,saved.max){
+    data$saved.max = apply(data[,c(var1,var2)],1,max)
+    data[,var1] = NULL
+    data[,var2] = NULL
+    data
+ }
> mydat = consolidate.fun(mydat,'a','b','var.max')
> mydat
   saved.max
1         5
2         6
3         3

(I changed the name of the data frame, because c is a function
name, and using it as a data frame name causes confusiion.)

The "<<-" operator only operates on complete objects, not
columns within a data frame.
 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu




On Thu, 18 Mar 2010, David Young wrote:

> Dear List,
>
> I'm getting the error: object of type 'closure' is not subsettable
> And am not sure how to get around the problem.  I've included two
> short code sets below.  One that shows what I want to do and works,
> but without using the function much, and another that tries to use the
> function but causes the error.
>
> # THIS WORKS AND SHOWS WHAT I'D LIKE TO DO
> a <- c(1,2,3)
> b <- c(5,6,0)
> c <- data.frame(a,b)
>
> # TAKES THE MAX OF TWO VARS AND SAVES IT TO A NEW VARIABLE AND DELETES OLD VARIABLES
> consolidate.fun <- function( data, var1, var2, saved.max ) {
> max <- apply( data[,c(var1, var2)], 1, max)
>
> # THIS WORKS BUT I HAVE TO CALL THE DATA FRAME BY NAME RATHER THEN USING THE FUNCTION DATA NAME
> c[,"var.max"] <<- max
> c$a <<- NULL
> c$b <<- NULL
> }
> consolidate.fun( data=c , var1="a", var2="b", saved.max="var.max" )
> c
>
> # THIS SHOWS THE MORE COMPLETE USE OF THE FUNCTION'S INTENT, BUT
> #  CAUSES THE ERROR IN R.
> a <- c(1,2,3)
> b <- c(5,6,0)
> c <- data.frame(a,b)
>
> # TAKES THE MAX OF TWO VARS AND SAVES IT TO A NEW VARIABLE AND DELETES OLD VARIABLES
> consolidate.fun <- function( data, var1, var2, saved.max ) {
> max <- apply( data[,c(var1, var2)], 1, max)
>
> # SOURCE OF ERROR.  I'VE TRIED CALLING THE DATA FRAME IN DIFFERENT
> #  WAYS, BUT NONE SEEM TO WORK FOR ME.
> data[, saved.max ] <<- max
> data[, var1 ] <<- NULL
> data[, var2 ] <<- NULL
> }
> consolidate.fun( data=c , var1="a", var2="b", saved.max="var.max" )
> c
>
> Any helpful comments would be appreciated.
>
>
>                          mailto:dyoung at telefonica.net
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list