[R] set specific contrasts using lapply
Rui Barradas
ruipbarradas at sapo.pt
Sun May 13 16:43:32 CEST 2012
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-request at r-project.org escreveu:
> Date: Fri, 11 May 2012 05:38:59 -0700 (PDT)
> From: Frank Paetzold<Frank.Paetzold at q-das.de>
> To:r-help at r-project.org
> Subject: [R] set specific contrasts using lapply
> Message-ID:<1336739939629-4626289.post at 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
More information about the R-help
mailing list