当因子水平仅具有一个水平时,将预测()与RcppArmadillo / RcppEigen一起使用

问题描述 投票:2回答:1

当因子变量只有一个级别时,我对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。我...

r rcpp predict
1个回答
0
投票

不是解决方案,而是对其发生原因的解释。

© www.soinside.com 2019 - 2024. All rights reserved.