2016-08-29 9 views
0

ループの繰り返しごとに、より多くの履歴データを使用してリニアモデルに適合させたいと思います。実際にコードは自明でなければなりません。問題は、DependentとIndependentが最初の反復の後にサイズが固定されていることです(コードに示されているように10のデータポイントから開始したいと思います)。動的なサイズにしたいのですが。ここでR:リニアモデルを構築するために動的サイズの配列を使用するループ構造

output1 <- rep(0, 127) 
output2 <- rep(0, 127) 
ret <- function(x, y) 
{ 
    for (i in 1:127) 
    { 
    Dependent <- y[1:(9+i)] 
    Independent <- x[1:(9+i)] 
    fit <- lm(Dependent ~ Independent) 
    nextInput <- data.frame(Independent = x[(10+i)]) 
    prediction <- predict(fit, nextInput, interval="prediction") 
    output1[i] <- prediction[2] 
    output2[i] <- prediction[3] 
    } 
} 
+0

あなたは[再現可能な例]を提供できます(http://stackoverflow.com/questions/5963269/how-to-make-a-great- r再生可能な例)?私は、標準データセットまたは乱数の再現性のあるベクトルで始めることをお勧めします。 – r2evans

+2

また、私はあなたが '1:(9 + i)'を代わりにしたいと思っています。検証するために '1:9 + 5'を実行してください。 – r2evans

+0

@ r2evans、それは問題を解決するはずです。現在のところ、この関数は1:9,2:10,3:11などの固定幅のローリングウィンドウの線形モデルに適合します(したがって、固定サイズのウィンドウ)。 – jav

答えて

1

思考だ、私はあなたの意図に近いよなら、私が知っている:私はモデル/予測のリストを作る代わりにforループを使用してい

set.seed(42) 
n <- 100 
x <- rnorm(n) 
head(x) 
# [1] 1.3709584 -0.5646982 0.3631284 0.6328626 0.4042683 -0.1061245 
y <- runif(n) 
head(y) 
# [1] 0.8851177 0.5171111 0.8519310 0.4427963 0.1578801 0.4423246 

ret <- lapply(10:n, function(i) { 
    dep <- y[1:i] 
    indep <- x[1:i] 
    fit <- lm(dep ~ indep) 
    pred <- 
    if (i < n) { 
     predict(fit, data.frame(indep = x[i+1L]), interval = "prediction") 
    } else NULL 
    list(fit = fit, pred = pred) 
}) 

注意。まったく同じではありませんが、this answerはこれが良いアイデアかもしれない理由を説明するまともな仕事をします。

の実行のいずれかから、モデルと予測:

ret[[50]] 
# $fit 
# Call: 
# lm(formula = dep ~ indep) 
# Coefficients: 
# (Intercept)  indep 
#  0.44522  0.02691 
# $pred 
#   fit  lwr  upr 
# 1 0.4528911 -0.1160787 1.021861 
summary(ret[[50]]$fit) 
# Call: 
# lm(formula = dep ~ indep) 
# Residuals: 
#  Min  1Q Median  3Q  Max 
# -0.42619 -0.22178 -0.00004 0.15550 0.53774 
# Coefficients: 
#    Estimate Std. Error t value Pr(>|t|)  
# (Intercept) 0.44522 0.03667 12.141 <2e-16 *** 
# indep  0.02691 0.03186 0.845 0.402  
# --- 
# Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 
# Residual standard error: 0.2816 on 57 degrees of freedom 
# Multiple R-squared: 0., Adjusted R-squared: -0.004966 
# F-statistic: 0.7134 on 1 and 57 DF, p-value: 0.4018 
+0

ありがとう、上記のコメントをご覧になれますか? – rocketman

関連する問題