【问题标题】:Factoring for linear models - Create lm with one factor线性模型的分解 - 用一个因子创建 lm
【发布时间】:2015-10-15 18:56:44
【问题描述】:

这个问题是this one 的更具体和简化的版本。

我使用的数据集对于单个 lmspeedlm 计算来说太大了。
我想将我的数据集分成更小的部分,但在这样做时,一个(或多个)列仅包含一个 factor
下面的代码是重现我的示例的最小值。在问题的底部,我会将我的测试脚本提供给感兴趣的人。

library(speedglm)

iris$Species <- factor(iris$Species)
i <- iris[1:20,]
summary(i)
speedlm(Sepal.Length ~ Sepal.Width + Species , i)

这让我得到以下错误:

Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
  contrasts can be applied only to factors with 2 or more levels

我试图分解iris$Species,但没有成功。我现在真的不知道如何解决这个问题。

如何将Species 包含到模型中?(不增加样本量)

编辑:
我知道我只有一个级别:“setosa”,但我仍然需要将它包含在线性模型中,因为我最终会使用更多因子更新模型,如下面的示例脚本所示


对于那些感兴趣的人,这里是我将用于我的实际数据集的示例脚本:

library(speedglm)

testfunction <- function(start.i, end.i) {
  return(iris[start.i:end.i,])
}

  lengthdata <- nrow(iris)
  stepsize <- 20

## attempt to factor
  iris$Species <- factor(iris$Species)

## Creates the iris dataset in split parts
  start.i <- seq(0, lengthdata, stepsize)
  end.i   <- pmin(start.i + stepsize, lengthdata)

  dat <- Map(testfunction, start.i + 1, end.i)

## Loops trough the split iris data
  for (i in dat) {
    if (!exists("lmfit")) {
      lmfit  <- speedlm(Sepal.Length ~ Sepal.Width + Species , i)
    } else if (!exists("lmfit2")) {
      lmfit2 <- updateWithMoreData(lmfit, i)
    } else {
      lmfit2 <- updateWithMoreData(lmfit2, i)
    }
  }
  print(summary(lmfit2))

【问题讨论】:

    标签: r lm factoring


    【解决方案1】:

    可能有更好的方法,但如果您对行重新排序,每个拆分将包含更多级别,因此不会导致错误。我创建了一个随机顺序,但您可能想要做一个更系统的方式。

    library(speedglm)
    
    testfunction <- function(start.i, end.i) {
        return(iris.r[start.i:end.i,])
    }
    
    lengthdata <- nrow(iris)
    stepsize <- 20
    
    ## attempt to factor
    iris$Species <- factor(iris$Species)
    
    ##Random order
    set.seed(1)
    iris.r <- iris[sample(nrow(iris)),]
    
    ## Creates the iris dataset in split parts
    start.i <- seq(0, lengthdata, stepsize)
    end.i   <- pmin(start.i + stepsize, lengthdata)
    
    dat <- Map(testfunction, start.i + 1, end.i)
    
    ## Loops trough the split iris data
    for (i in dat) {
        if (!exists("lmfit")) {
            lmfit  <- speedlm(Sepal.Length ~ Sepal.Width + Species , i)
        } else if (!exists("lmfit2")) {
            lmfit2 <- updateWithMoreData(lmfit, i)
        } else {
            lmfit2 <- updateWithMoreData(lmfit2, i)
        }
    }
    print(summary(lmfit2))
    

    编辑 您可以使用模除法以系统的方式生成展开的索引向量,而不是随机顺序:

    spred.i <- seq(1, by = 7, length.out = 150) %% 150 + 1
    iris.r <- iris[spred.i,]
    

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 2015-02-21
      • 1970-01-01
      • 2020-01-26
      相关资源
      最近更新 更多