Hello,

The value change inside a function's body is lost on exit.
You have changed the value of a copy of the argument passed to the function. That copy exists in the function's environment only. And the original exists in another environment, the caller's, the parent frame. (.GlobalEnv?)
This is valid for contrasts or for any other change you make.
In the case of contrasts, the loop is better, you will always have to check wether the object is a factor or logical vector before assigning different contrasts levels to it, so you can not use

contrasts(df or list) <- lapply(whatever)

Hope this helps,

Rui Barradas

Em 12-05-2012 11:00, r-help-requ...@r-project.org escreveu:
Date: Fri, 11 May 2012 05:38:59 -0700 (PDT)
From: Frank Paetzold<frank.paetz...@q-das.de>
To:r-help@r-project.org
Subject: [R] set specific contrasts using lapply
Message-ID:<1336739939629-4626289.p...@n4.nabble.com>
Content-Type: text/plain; charset=us-ascii

I have the following data set

>  data
    A  B  X1  X2   Y
1 A1 B1 1.1 2.9 1.2
2 A1 B2 1.0 3.2 2.3
3 A2 B1 1.0 3.3 1.6
4 A2 B2 0.5 2.6 3.1

>  sapply(data, class)
         A         B        X1        X2         Y
  "factor"  "factor" "numeric" "numeric" "numeric"

I'd like to set a specific type of contrasts to all the categorical factors
(here A and B).
In a loop, this can be done like this:

for (i in 1:length(data))
{
   if (class(data[[i]]) == 'factor')
   {
     contrasts(data[[i]], length(levels(data[[i]])))<-
contr.treatment(levels(data[[i]]), contrast=FALSE);
   }
}

Can i do this without the loop?

I tried to use the function

set.contrasts<- function(x)
{
   if (class(x) == 'factor')
   {
     contrasts(x, length(levels(x)))<- contr.treatment(levels(x),
contrast=FALSE);
   }
}

in

lapply(data, set.contrasts)

However, it doesn't work.

Any ideas?

Thank You

______________________________________________
R-help@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.

Reply via email to