0

我正在运行一些模拟,我想将线性模型拟合到我的数据子集:

library(reshape2)
library(plyr)

all <- mutate(iris, mean_width = ave(Petal.Width, Petal.Length))
str(all)

## want to minimise sum(|y*polynomial(x) - z|^2) for each id
## in the region where x != exclude

weighted_difference <- function(d, n=4, exclude = c(2.5, 3), ...){

  sub <- subset(d, !(Sepal.Width > exclude[1] &
                     Sepal.Width < exclude[2]))
  fit <-  lm(mean_width ~ I(poly(Petal.Length, n, raw=TRUE)*Petal.Width) + Petal.Width - 1, data = sub)
  mutate(d, predict = predict(fit, d),
         difference = Petal.Width - predict )
}

results <- ddply(all, "Species", weighted_difference)

这行得通,但我想使用一种更简单的方法,首先为适合的数据创建一个新的 data.frame,

  exclude <- c(3, 6)
  sub <- subset(all, !(x > exclude[1] & x < exclude[2]))

适合所有情况,

 fits <- lm(z ~ I(poly(x, n, raw=TRUE)*y) + y - 1 | id, data = sub)

(这... | id显然是无效的语法)

并立即对完整数据使用预测,

all <- mutate(all, predict = predict(fits, all), difference = y - predict )

有没有lm()像这样使用的技巧?还是更好的解决方案?谢谢。

4

1 回答 1

2

lmList(from )做nlme你想做的事吗?

library(nlme)
fits <- lmList(z ~ I(poly(x, n, raw=TRUE)*y) + y - 1 | id, data = sub)
于 2012-06-18T10:02:37.097 回答