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
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
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