如何获得迭代的每个输出

时间:2019-05-17 06:20:10

标签: r loops

我必须对此SIMPLS函数进行1000次迭代才能获得系数的值。我的问题是如何获取每次迭代的系数值?我可以打印输出以进行迭代吗?

n = 10
k = 20
a = 2
coef = matrix(0,nrow=20, ncol=10)
for (i in 1:1000) {
  t[,i] = matrix(rnorm(n%*%a,0,1), ncol=a)   # n x a
  p[,i] = matrix(rnorm(k%*%a,0,1), ncol=a)   # k x a
  B[,i] = matrix(rnorm(k,0,0.001), nrow=k, ncol=1)   # k x 1
  e[,i] = matrix(rcauchy(n,location=0,scale=1), nrow=n, ncol=1)##standard cauchy
  x[,i] = t%*%t(p)              ## explanatary variable xi
  y[,i] = (t%*%(t(p)%*%B)) + e  ## response variable yi
  simpls <- function(y, x, a) { 
    n <- nrow(x)
    k <- ncol(x)
    m <- NCOL(y)
    y <- matrix(y)
    Ps <- matrix(0, k, a)
    Cs <- matrix(0, m, a)
    Rs <- matrix(0, k, a)
    Ts <- matrix(0, n, a)
    mx <- apply(x, 2, mean)
    sdx <- apply(x, 2, sd)
    x <- sapply(1:k, function(i) (x[,i]-mx[i]))
    my <- apply(y, 2, mean)
    sdy <- apply(y, 2, sd)
    y <- sapply(1:m, function(i) (y[,i]-my[i]))
    S <- t(x)%*%y
    Snew <- S
    for (i in 1:a) {
      rs <- svd(Snew)$u[,1,drop=FALSE]
      rs <- rs/norm(rs,type="F")
      ts <- x%*%rs
      ts <- ts/norm(ts,type="F")
      ps <- t(x)%*%ts
  cs <- t(y)%*%ts
  Rs[,i] <- rs
  Ts[,i] <- ts
  Ps[,i] <- ps
  Cs[,i] <- cs
  Snew <- Snew-Ps[,1:i]%*%solve(t(Ps[,1:i])%*%Ps[,1:i])%*%t(Ps[,1:i])%*%Snew
}
coef[,i] <- matrix(drop(Rs%*%(solve(t(Ps)%*%Rs)%*%t(Cs))))
yfit <- x%*%coef
orgyfit <- yfit+my
res <- y-yfit
SSE <- sum((y-yfit)^2)
scale <- sqrt(SSE/(n-a))
stdres <- sapply(1:m, function(i) (res[,i]-mean(res[,i]))/sqrt(var(res[,i])))
hatt <- diag(Ts%*%solve(t(Ts)%*%Ts)%*%t(Ts))
result <- list(coef=coef, fit=orgyfit, res=res, SSE=SSE,scale=scale, stdres=stdres, leverage=hatt,Ts=Ts,Rs=Rs,Ps=Ps,Cs=Cs)

  }
}
print(coef)

1 个答案:

答案 0 :(得分:0)

您只需将coef添加到向量中即可进行每次迭代。我在这里创建了一个示例:

coef_vector <- NULL
for (i in 1:10) {
  loop_coef <- i*2
  coef_vector <- c(coef_vector, loop_coef)
}

结果:

> coef_vector
 [1]  2  4  6  8 10 12 14 16 18 20
> 

当然,如果您的变量比变量更复杂,则可以将其添加到列表中,而不是向量中。