Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - How to name contrasts in a dataframe

Tags:

dataframe

r

Let's assume, I have a dataframe:

xyz <- c(1,2,3,4,5,6)
zyx <- c("A", "B", "C", "A", "B", "C")
zyx <- factor(zyx)
myframe <- data.frame(xyz, zyx)

Now I want to compute constrast for the zyx-Variable. I use:

contrasts(myframe$zyx) <- contr.treatment(3, base=3)

If I'm now looking at the variable myframe$zyx, I get:

[1] A B C A B C
attr(,"contrasts")
  1 2
A 1 0
B 0 1
C 0 0
Levels: A B C

But I want to have the contras not named as "1" or "2", but as something like "contr_A_vs_C" and "contr_B_vs_C".

Do you have any ideas?

EDIT:

Ok, seems to be no easy question. Let me be more straightforward:

Is there a "name" command within the contrasts function, which can be addressed?

For example, if you do a linear regression, you can adress the model estimates vie direct command, for example, if you want to have the values für R squared, you can type:

rsquared <- regressionmodel$r.squared

Maybe, there's something similar in the contrasts, like

dataframe$contrast.names <- ...

?

like image 433
deschen Avatar asked Feb 03 '26 09:02

deschen


2 Answers

The matrix that you are referring to are stored as an attribute to the column you've specified. It can be accessed directly as follows:

attr(myframe$zyx, "contrasts")
#   1 2
# A 1 0
# B 0 1
# C 0 0

Thus, you can use colnames as usual (but I don't know if that breaks anything later on that might use the default output values of contrasts or contr.treatment).

colnames(attr(myframe$zyx, "contrasts")) <- 
  c("contr_A_vs_C", "contr_B_vs_C")

myframe$zyx
# [1] A B C A B C
# attr(,"contrasts")
#   contr_A_vs_C contr_B_vs_C
# A            1            0
# B            0            1
# C            0            0
# Levels: A B C
like image 176
A5C1D2H2I1M1N2O1R2T1 Avatar answered Feb 05 '26 04:02

A5C1D2H2I1M1N2O1R2T1


The n parameter of contr.treatment(n=3, base=3) alternatively takes a list of names. I'm quite satisfied with

contrasts(myframe$zyx) <- contr.treatment(n=levels(myframe$zyx), base=3)
contrasts(myframe$zyx)
#   A B
# A 1 0
# B 0 1
# C 0 0

or, if you prefer

contrasts(myframe$zyx) <- contr.treatment(n=c("contr_A_vs_C", "contr_B_vs_C", "none"), base=3)
contrasts(myframe$zyx)
#   contr_A_vs_C contr_B_vs_C
# A            1            0
# B            0            1
# C            0            0
like image 42
phispi Avatar answered Feb 05 '26 05:02

phispi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!