hncl
hncl

Reputation: 1

dynamic loop in R

I have a vector x :

x<-rpois(16,lambda=10)

and a lookup table named u3 :

minx<-min(x)
maxx<-max(x)
dg<-maxx-minx
k<-5
sa<-ceiling(dg/k)

u1=data.frame(seq(minx,maxx,sa))
colnames(u1)<-"x"

u2<-NULL
for (i in 1:k)
{
 u2[i]<-u1[i,] + sa-1
}


u2<-as.data.frame(u2)
colnames(u2)<-"y"

u3<-cbind(u1,u2)

for(i in 1:nrow(u2))
{
 u3$range[i]<-paste(u1[i,],u2[i,],sep="-")
}

print(u3)

my u3 data.frame like :

   x  y range

1  3  5   3-5
2  6  8   6-8
3  9 11  9-11
4 12 14 12-14
5 15 17 15-17

I want to do a calculation here: I want to every x vector look in u3 data frame variables in colums 1,2 and then if condition true,so if x values are in range,count the x values which are in the range of u3 dataframe and write the count to u3 dataframe as a new column.

something like this :

count=0
for(i in 1:length(x))
{
  for(j in 1:nrow(u3))
  {
   u3$count[j]<-if(x[i]>=u3[j,1] & x[i]<=u3[j,2]) {count=count + 1}
  }
}

but i can't make it.

Do you have an idea about it ? How can I deal such a problem ? I dont know how to tell R to look dynamically to lookup table and write the count of it. I want such a desired output

   x  y range  count

1  3  5   3-5   2
2  6  8   6-8   5
3  9 11  9-11   1
4 12 14 12-14   4
5 15 17 15-17   3

Thank you

Upvotes: 0

Views: 919

Answers (1)

Ananta
Ananta

Reputation: 3711

with set.seed(0)

 x
 [1] 13  8 14 14 11 14 12 11  9 14 11  8  2  8 10  7
 u3
   x  y range
1  2  4   2-4
2  5  7   5-7
3  8 10  8-10
4 11 13 11-13
5 14 16 14-16

 cbind(u3,data.frame(table(findInterval(x,u3$x))))
   x  y range Var1 Freq
1  2  4   2-4    1    1
2  5  7   5-7    2    1
3  8 10  8-10    3    5
4 11 13 11-13    4    5
5 14 16 14-16    5    4

Keep in mind, I used findInterval(x,u3$x) it only works for your example because your groupings are (x,y] ie (x inclusive, y non-inclusive)

Upvotes: 0

Related Questions