Per unique value cycle

Is it possible to write a for loop with discrete levels?

I have a vector like this:

a<-c(1,1,1,1,1,3,3,5,11,18 ....1350) 

This is an increasing series, but does not match the logical order;

I would like to start the 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 
+7
source share
1 answer

Your initial mistake is that you are confusing the loop by index with the loop over the elements of your vector.

If you want to iterate over the unique elements of your vector, use:

 for(i in unique(a)) 

I guess what you wanted to do. But an alternative is to loop over a unique vector index:

 for(i in 1:length(unique(a))){ this.a <- unique(a)[i] } 

These are two equivalents, but the second one will let you know the current index (if you ever needed one).

+15
source

All Articles