# Find the frequency of successive occurrences less than equal to a threshold in an R data frame column?

R ProgrammingServer Side ProgrammingProgramming

#### Artificial Intelligence : The Future Of Programming

15 Lectures 54 mins

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

To find the frequency of successive occurrences less than a threshold value in an R data frame column, we can use rle function along with sum function.

Check out the below given examples to understand how it can be done.

## Example 1

Following snippet creates a sample data frame −

x<-round(rnorm(20,1,2.5),0)
df1<-data.frame(x)
df1

The following dataframe is created −

    x
1   1
2   4
3  -2
4  -3
5  -3
6  -4
7   3
8  -4
9   2
10  1
11  4
12  2
13  1
14 -1
15  4
16 -4
17  1
18 -1
19 -2
20 -1

To find the frequency of success occurrences less than equal to 1 in column x, add the following code to the above snippet −

x<-round(rnorm(20,1,2.5),0)
df1<-data.frame(x)
sum(rle(df1$x<=1)$values)

## Output

If you execute all the above given snippets as a single program, it generates the following output −

 6

## Example 2

Following snippet creates a sample data frame −

y<-round(rnorm(20,5,10),0)
df2<-data.frame(y)
df2

The following dataframe is created −

     y
1   22
2    4
3    5
4   18
5   16
6   18
7    3
8   -4
9   22
10   8
11   5
12   6
13 -11
14  -7
15  -4
16   7
17  18
18  11
19  -6
20  -9

To find the frequency of success occurrences less than equal to 5 in column y, add the following code to the above snippet −

y<-round(rnorm(20,5,10),0)
df2<-data.frame(y)
sum(rle(df2$y<=5)$values)

## Output

If you execute all the above given snippets as a single program, it generates the following output −

 5

## Example 3

Following snippet creates a sample data frame −

z<-sample(0:5,20,replace=TRUE)
df3<-data.frame(z)
df3

The following dataframe is created −

   z
1  2
2  4
3  3
4  5
5  4
6  2
7  3
8  2
9  0
10 3
11 4
12 0
13 4
14 3
15 3
16 0
17 3
18 3
19 3
20 3

To find the frequency of success occurrences less than equal to 4 in column z, add the following code to the above snippet −

z<-sample(0:5,20,replace=TRUE)
df3<-data.frame(z)
sum(rle(df3$z<=4)$values)

## Output

If you execute all the above given snippets as a single program, it generates the following output −

 2