I am using the script below to loop over the data w
three times and it outputs three results when I use the print to display them. I am trying to output the results to an assigned variable my_vector(j)
but only the last iteration results are displayed. How can I save the results for each iteration in an array?
DU<-c(70,85,95)
a<-1-sqrt(3)*((100-DU)/130)
my_vector = c()
w<-c(0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5)
w_i<-1/w
for (i in 1:length(DU)){
for (j in 1:length(w)){
if (w_i[j] > 2-a[i]) {
E[j]<-1
} else if (w_i[j]<2-a[i]) {
E[j]<-((a[i]*w[j]+1)^2-4*w[j])/(4*(a[i]-1)*w[j]^2)
} else {
E[j]=w_i[j]
}
my_vector[j]<-(E[j])
print(E[j])
}
my_vector[j]<-(E[j])
}
Because when you call my_vector[j]<-(E[j])
, j
only takes values between 1 and length(w)
, so for each iteration of the loop i
you rewrite everything (each time you change of value for i
then j
restarts to 1).
Replace by:
my_vector[j + length(w)*(i-1)]<-(E[j])
Also, I think that you should remove the last line with
my_vector[j]<-(E[j])
As it is outside of the loop on j
(or at least I don't understand why it is here)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.