Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201977

for loop transferring to foreach in R language

$
0
0

I am trying to find a connection between for loop and foreach function, but all the examples are so basic that I am lost in my huge loop. Can someone help me to understand how to make it?

I have these data:

n.s<-20*(1:250) #Suite de valeurs de n
ASE.s<-rep(NA,length(n.s)) #Vecteurs vides pour stocker les valeurs calculées
h.s<-rep(NA,length(n.s))
max.n.s <- max(n.s)

x_i<-(1:max.n.s)/max.n.s #Échantillon de la variable design pour la valeur plus grande de n.

#Calcul de l'échantillon réponse pour n maximale
eta<-rnorm(max.n.s,0,1)

epsilon<-rep(NA,max.n.s)
epsilon[1]<-0
for (i in 2:max.n.s){
  epsilon[i]<-eta[i]*sqrt(sigma^2*(1-alpha)+alpha*epsilon[i-1]^2)
}

Y_i<-g(x_i)+epsilon #Échantillon réponse pour n maximale

Created function:

K<-function(u){
  0.5*(abs(u)<1)
}
# on a choisi la noyaux rectangulaire parce que il est pair et à support compact

# creation de fonction de regression reel g
g <- function(x){
  sin(2*pi*x)
}

And here is my for loop:

for (m in n.s){

  #Création de l'échantillon comme un sous-ensemble de l'échantillon déjà calculé
  X_m<-x_i[seq(1,max.n.s,length=m)]
  Y_m<-Y_i[seq(1,max.n.s,length=m)]

  #Ré-définition des fonctions pour la taille m
  g_hat_m<-Vectorize(function(x,h){1/(m*h)*sum(Y_m*K((x-X_m)/h))})
  ASE_m<-function(t){1/m*sum((g_hat_m(X_m,t)-g(X_m))^2)}
  CV_m<-function(t){
    L<-K(0)/(m*t)
    return(1/m*sum(((g_hat_m(X_m,t)-Y_m)/(1-L))^2))}

  #Calcul des valeurs optimales
  opt_i<-optimize(ASE_m,lower=0.001,upper=1,maximum=FALSE)
  h0_hat_i<-opt_i$minimum
  h_hat_i<-optimize(CV_m,lower=0.001,upper=1,maximum=FALSE)$minimum
  ASE.s[which(m==n.s)]<-ASE_m(h_hat_i)/opt_i$objective
  h.s[which(m==n.s)]<-h_hat_i/h0_hat_i
}

Should I just change to foreach(m = n.c) %dopar% ? I tried , but got only 130+ values and the others were NA. So I guess the logic of for each should be changed :/


Viewing all articles
Browse latest Browse all 201977

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>