Is it possible to write a for loop with discrete levels?
I have a vector of the following form:
a<-c(1,1,1,1,1,3,3,5,11,18 ....1350)
it is an increasing series but does not follow any logical order;
I would like to run a for loop using levels(a) as an argument:
for i in 1:levels(a)
I get the following error:
In 1:levels_id :
numerical expression has 1350 elements: only the first used
Your initial mistake is that you are confusing looping over the index with looping over the elements of your vector.
If you want to loop over unique elements of your vector then use:
for(i in unique(a))
I assume that's what you wanted to do. But the alternative is to loop over the unique vector's index:
for(i in 1:length(unique(a))){
this.a <- unique(a)[i]
}
These two are equivalent, but the second will enable you to know the current index as well (if you ever needed it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With