R - 如何在数据框中命名对比

时间:2022-07-11 01:12:34

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:

现在我想计算zyx-Variable的约束。我用:

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

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

如果我现在正在查看变量myframe $ zyx,我得到:

[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".

但是我希望对比不是“1”或“2”,而是像“contr_A_vs_C”和“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:

例如,如果进行线性回归,则可以通过直接命令对模型估计进行处理,例如,如果要将值设置为R平方,则可以键入:

rsquared <- regressionmodel$r.squared

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

也许,在对比中有类似的东西,比如

dataframe$contrast.names <- ...

?

1 个解决方案

#1


1  

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(但我不知道以后是否会破坏任何可能使用对比或控制处理的默认输出值)。

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

#1


1  

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(但我不知道以后是否会破坏任何可能使用对比或控制处理的默认输出值)。

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