Ivan
Ivan

Reputation: 76

Save values from FOR loop for further analysis

How do I save the values from the For Loop from the following code? When I pint the variable "lm5", it has a total of two values. When I tried to save it to a new variable, it only shows the last value.

Ideally, I would like to save the lm5,lm10,lm20 for another round of IF statement analysis. Could you please advise how to proceed? Thanks in advance!

even<-c(2,4)

for( i in even){
  m5<-rollmean(test[,i],5,fill=NA)
  m10<-rollmean(test[,i],10,fill=NA)
  m20<-rollmean(test[,i],20,fill=NA)
  lm5<-tail(m5[!is.na(m5)],1)
  print(lm5)
}

Upvotes: 2

Views: 40

Answers (1)

Sada93
Sada93

Reputation: 2835

There are a few data structures at your disposal to achieve this.

Vectors

even<-c(2,4)
lm5_vector = c()
for( i in even){
  m5<-rollmean(test[,i],5,fill=NA)
  lm5_vector<-c(lm5_vector,tail(m5[!is.na(m5)],1))
}
print(lm5)

This will store elements of each iteration into a vector. Finally printing both elements of the vector. We are storing the result in what is called an atomic vector. The disadvantage of this is that you would need to initialize a new vector for lm10, lm20 and so on.

The alternative is the following.

Lists + Vectors

The list data structure allows us to store all the values you wish to store under one convenient name. Lists allow us to nest other data structures. Hence we nest an atomic vector under a list.

even<-c(2,4)
result_list = list(lm5 = c(),lm10 = c(),lm20 = c())
for( i in even){
  m5<-rollmean(test[,i],5,fill=NA)
  result_list$lm5<-c(result_list$lm5,tail(m5[!is.na(m5)],1))
}
print(result_list)

Upvotes: 2

Related Questions