user1723765
user1723765

Reputation: 6399

For loop over unique values

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

Upvotes: 15

Views: 40858

Answers (1)

MattLBeck
MattLBeck

Reputation: 5831

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).

Upvotes: 29

Related Questions