How to find the percentage of values that lie within a range in a single column R matrix?

R ProgrammingServer Side ProgrammingProgramming

To find the percentage of values that lie within a range in single column R matrix, we can follow the below steps −

  • First of all, create a matrix.

  • Then, use sum function along with extreme values for range and length function to find the percentage of values that lie within that range.

Example

Create the data frame

Let’s create a data frame as shown below −

M<-matrix(sample(1:100,30))
M

Output

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

     [,1]
[1,]  52
[2,]  49
[3,]  73
[4,]   8
[5,]  89
[6,]  17
[7,]   1
[8,]  47
[9,]  70
[10,] 24
[11,] 30
[12,] 63
[13,]  4
[14,] 33
[15,] 76
[16,] 37
[17,] 96
[18,] 53
[19,] 32
[20,] 65
[21,] 61
[22,] 87
[23,] 54
[24,] 34
[25,] 97
[26,]  3
[27,] 31
[28,] 45
[29,] 38
[30,] 84

Find the percentage of values that lie within a range

Using sum function along with the range that is 33 and 75 and length function to find the percentage of values that lie within 33 and less than equal to 75 −

M<-matrix(sample(1:100,30))
sum(M[,]>33 & M[,1]<=75)/length(M[])

Output

[1] 0.4666667
raja
Updated on 16-Nov-2021 05:48:18

Advertisements