[R] set specific contrasts using lapply

Frank Paetzold Frank.Paetzold at q-das.de
Fri May 11 14:38:59 CEST 2012


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

--
View this message in context: http://r.789695.n4.nabble.com/set-specific-contrasts-using-lapply-tp4626289.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list