在回归方程中使用居中变量时是否必须保持矩阵形式?
我使用带有
scale
和 center=T
的 scale=F
函数将一些变量居中。然后我将这些变量转换为数值变量,以便我可以出于其他目的操作数据框。然而,当我运行方差分析时,我得到的 F 值略有不同,只是对于那个变量,其他都是一样的。
编辑:
这两者有什么区别:
scale(df$A, center=TRUE, scale=FALSE)
这将在您的 data.frame 中嵌入一个矩阵
和
scale(df$A, center=TRUE, scale=FALSE)
df$A = as.numeric(df$A)
哪个使变量 A 成为数字,并删除变量中的矩阵符号?
我正在尝试做的事情的例子,但这个例子并没有导致我遇到的问题:
library(car)
library(MASS)
mtcars$wt_c <- scale(mtcars$wt, center=TRUE, scale=FALSE)
mtcars$gear <- as.factor(mtcars$gear)
mtcars1 <- as.data.frame(mtcars)
# Part 1
rlm.mpg <- rlm(mpg~wt_c+gear+wt_c*gear, data=mtcars1)
anova.mpg <- Anova(rlm.mpg, type="III")
# Part 2
# Make wt_c Numeric
mtcars1$wt_c <- as.numeric(mtcars1$wt_c)
rlm.mpg2 <- rlm(mpg~wt_c+gear+wt_c*gear, mtcars1)
anova.mpg2 <- Anova(rlm.mpg2, type="III")
我会尝试回答你的两个问题
在回归方程中使用居中变量时是否必须保持矩阵形式?
我不确定你的意思,但是你可以去掉你从
scale()
得到的 center 和 scale 属性,如果那是你所指的。您可以在下面的示例中看到,无论是否为“矩阵形式”,您都会得到相同的答案。
这两者有什么区别:
scale(A, center=TRUE, scale=FALSE)
这将在您的 data.frame 中嵌入一个矩阵
和
scale(df$A, center=TRUE, scale=FALSE) df$A = as.numeric(df$A)
从
scale()
的帮助文件我们看到它返回,
“对于 scale.default,居中、缩放的矩阵。”
您将返回一个具有缩放和居中属性的矩阵。
as.numeric(AA)
剥离那些属性,这是您的第一种方法和第二种方法之间的区别。 c(AA)
做同样的事情。我猜as.numeric()
要么调用c()
(通过as.double()
),要么使用与它相同的方法。
set.seed(1234)
test <- data.frame(matrix(runif(10*5),10,5))
head(test)
X1 X2 X3 X4 X5
1 0.1137034 0.6935913 0.31661245 0.4560915 0.5533336
2 0.6222994 0.5449748 0.30269337 0.2651867 0.6464061
3 0.6092747 0.2827336 0.15904600 0.3046722 0.3118243
4 0.6233794 0.9234335 0.03999592 0.5073069 0.6218192
5 0.8609154 0.2923158 0.21879954 0.1810962 0.3297702
6 0.6403106 0.8372956 0.81059855 0.7596706 0.5019975
# center and scale
testVar <- scale(test[,1])
testVar
[,1]
[1,] -1.36612292
[2,] 0.48410899
[3,] 0.43672627
[4,] 0.48803808
[5,] 1.35217501
[6,] 0.54963231
[7,] -1.74522210
[8,] -0.93376661
[9,] 0.64339300
[10,] 0.09103797
attr(,"scaled:center")
[1] 0.4892264
attr(,"scaled:scale")
[1] 0.2748823
# put testvar back with its friends
bindVar <- cbind(testVar,test[,2:5])
# run a regression with 'matrix form' y var
testLm1 <- lm(testVar~.,data=bindVar)
# strip non-name attributes
testVar <- as.numeric(testVar)
# rebind and regress
bindVar <- cbind(testVar,test[,2:5])
testLm2 <- lm(testVar~.,data=bindVar)
# check for equality
all.equal(testLm1, testLm2)
[1] TRUE
lm()
似乎返回相同的东西所以看起来它们都是一样的。