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

R ProgrammingServer Side ProgrammingProgramming

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

  • First of all, create a data frame.

  • 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 −

Var<-sample(1:100,30)
df<-data.frame(Var)
df

Output

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

   Var
1  39
2  40
3  96
4  37
5  97
6  23
7  35
8  47
9  60
10 63
11 74
12 91
13  6
14 54
15  5
16 90
17 68
18 32
19 83
20 29
21 100
22 52
23 26
24 16
25 10
26 65
27 55
28 84
29 92
30 15

Find the percentage of values that lie within a range

Using sum function along with the range that is 10 and 91 and length function to find the percentage of values that lie within this range −

Var<-sample(1:100,30)
df<-data.frame(Var)
sum(df$Var>10 & df$Var<91)/length(df$Var)

Output

[1]  0.8
raja
Published on 08-Nov-2021 10:47:26

Advertisements