Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop over unique values

Tags:

r

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
like image 982
user1723765 Avatar asked Dec 17 '12 14:12

user1723765


1 Answers

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

like image 102
MattLBeck Avatar answered Sep 20 '22 13:09

MattLBeck