How to create a table of frequency for range of values in an R data frame column?

R ProgrammingServer Side ProgrammingProgramming

To create a table of frequency for range of values in an R data frame column, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use table function with cut function to create the table of frequency for range of values.

Example 1

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-sample(1:10,20,replace=TRUE)
df1<-data.frame(x)
df1

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

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

Create a table of frequency for range of values

Using table function along with cut function to create a table of frequency for range of values say 1 to 11 using column x of data frame df1 −

 Live Demo

x<-sample(1:10,20,replace=TRUE)
df1<-data.frame(x)
table(cut(df1$x,breaks=seq.int(from=1,to=11,by=2)))

Output

(1,3] (3,5] (5,7] (7,9] (9,11]
  5     5     3     5      2

Example 2

Create the data frame

Let's create a data frame as shown below −

 Live Demo

y<-round(rnorm(20),1)
df2<-data.frame(y)
df2

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

   y
1 0.2
2 1.0
3 0.4
4 0.5
5 -1.4
6 -0.9
7 1.2
8 -0.8
9 -0.6
10 -0.1
11 -0.1
12 0.5
13 -1.3
14 0.3
15 -1.9
16 0.9
17 -1.6
18 1.0
19 -0.3
20 0.0

Create a table of frequency for range of values

Using table function along with cut function to create a table of frequency for range of values say -2 to 1.5 using column y of data frame df2 −

 Live Demo

y<-round(rnorm(20),1)
df2<-data.frame(y)
table(cut(df2$y,breaks=seq.int(from=-2,to=1.5,by=0.5)))

Output

(-2,-1.5] (-1.5,-1] (-1,-0.5] (-0.5,0] (0,0.5] (0.5,1] (1,1.5]
   2          2          3       4       5       3       1
raja
Published on 07-Aug-2021 09:46:31
Advertisements