Skip to content

Assign factor and levels inside function

1 message · Tim Howard

#
Aha!
   You've just opened the door to another level for this blundering R
user.  I even went back to my well-used copy of "An Introduction to R"
to see where I missed this standard approach for processing new data. 
Nothing clear but certainly alluded to in many of the function examples.
 I don't know why I was stuck in that rut.

I'm sure 99.9% of you on this list know this, but... To be clear for
anyone searching these archives later:  Don't bother to ask your
function to make assignments to pos=1 (the global environment), just do
the assignment yourself when calling the function. For example, instead
of coding a function call like this:

processData(dat)

to assign the processed data to pos=1, simply make the assignment when
calling the function:

dat <- processData(dat)


Thanks for being gentle on me, Andy.

Tim
Tim,
was
a
Ouch!  "levels<-" is generic, and the default method simply attach the
levels attribute to the object.  You need to coerce the object into a
factor
explicitly.
I believe the canonical ways of doing something like this in R is
something
along the line of:

processData <- function(dat) {
    dat$f1 <- factor(dat$f1, levels=...)
    ...  ## any other manipulations you want to do
    dat
}

Then when you get new data, you just do:

newData <- processData(newData)

HTH,
Andy
define
only
contains
Station,
MSD
the
------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachments,...{{dropped}}