当因子变量只有一个级别时,我对predict()
和RcppArmadillo
包中RcppEigen
函数的使用有疑问。我使用iris
数据集在下面建立了MWE。
我想首先使用RcppArmadillo
估计线性回归模型,然后使用它来预测值。我用于估计的数据包含因子变量(具有多个级别且没有NA
)。我要进行的预测在某一方面有点不寻常:我想对所有观测值使用相同的因子水平来预测值(该水平处于估计中使用的水平)。在下面的示例中,这意味着我想像所有观察值均来自“ versicolor”物种一样来预测Sepal.Length
。
[当我使用lm()
函数估算模型时效果很好,但不适用于RcppArmadillo::fastLm()
或RcppEigen::fastLm()
函数。我收到以下错误:Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels
。如果缺少因子水平之一,则再次发生相同的错误。我很理解为什么至少需要两个级别才能进行估计,但是我不明白为什么一旦模型被正确估计后,只有一个级别对预测来说是一个问题。
显而易见的解决方案是使用lm()
而不是fastLm()
,但是不幸的是这是不可能的,因为我的数据很大。经过反复试验,我发现了这种肮脏的解决方法:
没有人有比这更好的解决方案,或者至少有一个解释为什么会出现此错误?
library(data.table)
# Loading iris data
iris <- as.data.table(iris)
# Estimating the model
model <-
RcppArmadillo::fastLm(Sepal.Length ~
factor(Species)
+ Sepal.Width
+ Petal.Length
+ Petal.Width,
data=iris)
summary(model)
####
#### Here is the error I don't understand
####
# This is the standard use of the predict function
iris2 <- copy(iris)
iris2[, predict := predict(model, iris2)]
# This is the way I want to use the predict function
# This does not work for some reason
iris2 <- copy(iris)
iris2[, Species := "versicolor"]
iris2[, predict2 := predict(model, iris2)]
####
#### This is a dirty work-around
####
# Creating a modified dataframe
iris3 <- copy(iris)
iris3[, `:=`(Species = "versicolor",
data = "Modified data")]
# copying the original dataframe
iris4 <- copy(iris)
iris4[, data := "Original data"]
# Stacking the original data and the modified data
iris5 <- rbind(iris3, iris4)
iris5[, predict := predict(model, iris5)]
# Keeping only the modified data
iris_final <- iris5[data == "Modified data"]
我有一个关于在因子变量只有一个级别的情况下将Rectpp()函数与RcppArmadillo和RcppEigen包一起使用的问题。我在下面使用虹膜数据集构建了MWE。我...
不是解决方案,而是对其发生原因的解释。