在R中的循环内调用先前保存的值

时间:2014-08-20 22:12:16

标签: r loops for-loop

我使用R很新,我真的很感激一些输入。我使用循环创建了几个子集(每次迭代一个)。然后我使用每个子集/迭代运行回归并保存系数(它们作为变量包含在每个子集/迭代中:列中所有行的单个值)。我想要做的是在迭代i中保存使用迭代i-1获得的系数(因为我想使用先前子集的系数和当前子集的变量进行预测)

有人可以帮我解决这个问题 感谢。

这是一个可重复的例子:

Data <- data.frame(
    X = sample(1:10),
    Y = sample(1:10)
)
Data$obs<-as.numeric(row.names(Data))
temp=NULL
obs=unique(Data$obs)
for (i in 2:length(obs)) {
    temp<-subset(Data, obs<=obs[i])
    ols <- lm(Y~X, data=temp)
    temp$intercept <-coef(summary(ols))["(Intercept)","Estimate"]
    temp$coefX <-coef(summary(ols))["X","Estimate"]

    #this is what i am trying to do
    temp$coefXprevious <- temp$coefX [i-1]

    write.csv(temp, paste(obs[i], ".csv", sep=""))
}

所以对于最后一个子集/迭代,我得到了:

X   Y   obs intercept   coefx   coefxprevious
8   5   1   9.8    -0.781818182 -0.781818182 
2   10  2   9.8    -0.781818182 -0.781818182 
10  1   3   9.8    -0.781818182 -0.781818182 
3   8   4   9.8    -0.781818182 -0.781818182 
9   2   5   9.8    -0.781818182 -0.781818182
5   4   6   9.8    -0.781818182 -0.781818182 
4   6   7   9.8    -0.781818182 -0.781818182 
7   3   8   9.8    -0.781818182 -0.781818182
6   9   9   9.8    -0.781818182 -0.781818182
1   7   10  9.8    -0.781818182 -0.781818182

这个输出很好但是最后一列。 我将不胜感激任何帮助。感谢

2 个答案:

答案 0 :(得分:1)

您正在循环的每次迭代中创建一个全新的temp。我想你想要这个:

Data <- data.frame(
  X = sample(1:10),
  Y = sample(1:10),
  intercept = rep(NA,10), coefX = rep(NA,10), coefXprevious = rep(NA,10)
)
Data$obs<-as.numeric(row.names(Data))

for (i in 2:length(obs)) {
  ols <- lm(Y~X, data=Data[Data$obs<=i,])
  Data$intercept[i] <-coef(summary(ols))["(Intercept)","Estimate"]
  Data$coefX[i] <-coef(summary(ols))["X","Estimate"]

  Data$coefXprevious[i] <- Data$coefX [i-1]

  write.csv(Data[Data$obs<-i,], paste(obs[i], ".csv", sep=""))
}

哪个会作为最后一个输出(但为什么还需要其他输出?):

    X  Y intercept      coefX coefXprevious obs

1   6  6        NA         NA            NA   1
2   9  4 10.000000 -0.6666667            NA   2
3   3  5  6.000000 -0.1666667    -0.6666667   3
4   8  9  5.071429  0.1428571    -0.1666667   4
5   2  2  2.580645  0.4677419     0.1428571   5
6   4  8  3.813559  0.3474576     0.4677419   6
7   1  1  2.363402  0.5592784     0.3474576   7
8   7  3  2.500000  0.4500000     0.5592784   8
9  10  7  2.500000  0.4500000     0.4500000   9
10  5 10  3.200000  0.4181818     0.4500000  10

答案 1 :(得分:0)

得到了!!!

Data <- data.frame(X = sample(1:10),Y = sample(1:10))
Data$obs<-as.numeric(row.names(Data))

temp=NULL
temp2=NULL
obs=unique(Data$obs)

for (i in 8:length(obs)){
    temp1<-subset(Data, obs<=obs[i-1])
    temp2<-subset(Data, obs<=obs[i])
    ols1 <- lm(Y~X, data=temp1) 
    ols2 <- lm(Y~X, data=temp2) 

    temp2$coefx <-coef(summary(ols2))["X","Estimate"]
    temp2$coefxprev <- coef(summary(ols1))["X","Estimate"]
    temp2$predict <-predict(ols1,temp2)

write.csv(temp2, paste(obs[i], ".csv", sep=""))
}