【问题标题】:How to apply a linear model to specific parts of a data frame? [duplicate]如何将线性模型应用于数据框的特定部分? [复制]
【发布时间】:2015-10-30 06:18:14
【问题描述】:

我正在使用包含 3 列的数据框 (dt):TimeTempSpecies,例如

 Temp Time    Species
 1   10   241 Species-X
 2   11   241 Species-X
 3   12   241 Species-X
 4   13   241 Species-Y
 5   14   241 Species-Y
 6   15   240 Species-Z
...  ...  ...     ...
 41  50   178 Species-Z

第三列有五个物种。 我想应用一个线性模型(lm),其中Temp 作为我的自变量,Time 作为因变量。 所以我想仅针对物种 X 或 Y 对其进行测试。此外,我想以给定的Temp 间隔(假设为 20 - 29 摄氏度)测试我的物种之一。 我试过了:

lm(Temp ~ Time, data = td[Species =  Species-Y])

for(i in unique(td$Species)){
model <- list(model)
model[i] <- lm(td$Time ~ td$Temp)
}

model <- function (dados) {
    return(lm(td$Time[,dados] ~ td$Temp[,dados]))
  }
model(dados = td$Species-X)

【问题讨论】:

  • 我会使用lmsubset功能... lapply(c("Species-X", "Species-Y"), function(x) lm(Time ~ Temp, data=td, subset=Species==x))
  • 您在上面的第一次尝试几乎可以工作......您需要使用引号,并且需要一个额外的逗号。所以试试lm(Temp ~ Time, data = td[td$Species == "Species-Y" , ])

标签: r subset lm


【解决方案1】:

基础 R 中的 by() 函数提供了一种解决方案:

by(td, td$Species, function(df) lm(df[,"Temp"] ~ df[,"Time"]))

如果您想为不同的子集制定不同的规则,您可能需要逐组进行。例如,要对 20-29(含)的温度执行 Species-Y,您可以运行:

lm(Temp ~ Time, data = td[td$Species == "Species-Y" & td$Temp >= 20 & td$Temp <= 29, ])

【讨论】:

  • 感谢您的回答,但我无法让它发挥作用。我可以t figure out what I am doing wrong... i keep getting these Warning messages: 1: In model.response(mf, "numeric") : using type = "numeric" with a factor response will be ignored 2: In Ops.factor(y, z$residuals) : ‘-’ not meaningful for factors ... But Ill 继续努力
  • 无论您在调用lm 时使用哪个变量作为y --- 并且从您的帖子中,我不确定哪个是--- 必须编码为一个因素。假设它是time。在运行by() 行之前,运行td$Time &lt;- as.numeric(td$Time) 然后尝试一下。
  • 成功了!我欠你很多时间!
  • 如果成功了,正式采纳答案会很有帮助。
  • 嗨 ulfelder,我确实赞成你的回答,但我是新来的,网站告诉我,我需要 15 次评估才能开始计票。如果有其他方式我可以正式接受您的回答,请直接说出来
猜你喜欢
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-05
  • 1970-01-01
  • 2014-10-10
  • 2021-06-17
  • 2019-01-06
相关资源
最近更新 更多