How to find the smallest number in an R data frame column excluding values zero or less?


To find the smallest number in an R data frame column excluding values zero or less, we can use min function along with subsetting of values greater than 0 through single square brackets.

For example, if we have a data frame called df that contains a column say X then the smallest number excluding values zero or less can be found by using the below command −

min(df[df$X>0,1])

Example 1

Following snippet creates a sample data frame −

x<-rnorm(20)
df1<-data.frame(x)
df1

The following dataframe is created −

     x
1  -0.3880970
2   0.3618485
3   0.5030129
4   1.3981004
5   1.3462107
6  -1.1734200
7  -0.4259265
8   0.6943913
9  -0.4037978
10 -0.6777677
11 -1.0339321
12  0.1048411
13  0.5757606
14  1.1436323
15 -1.0120865
16  0.6414445
17 -0.6199611
18  1.3455134
19  0.7757701
20 -0.7801373

To find the smallest values after excluding values less than 0 in x, add the following code to the above snippet −

x<-rnorm(20)
df1<-data.frame(x)
min(df1[df1$x>0,1])

Output

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

[1] 0.1048411

Example 2

Following snippet creates a sample data frame −

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

The following dataframe is created −

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

To find the smallest values after excluding values less than 0 in y, add the following code to the above snippet −

y<-rpois(20,1)
df2<-data.frame(y)
min(df2[df2$y>0,1])

Output

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

[1] 1

Example 3

Following snippet creates a sample data frame −

z<-rnorm(20,1,0.5)
df3<-data.frame(z)
df3

The following dataframe is created −

      z
1  1.1018723
2  0.5307347
3  1.0830877
4  1.2370675
5  0.7851581
6  1.4266275
7  1.4885041
8  0.7601659
9  0.9276275
10 1.1924751
11 1.3655478
12 0.1325154
13 0.5545835
14 1.2137084
15 1.6315352
16 1.1455820
17 0.9393499
18 0.8205281
19 0.7663259
20 0.6274036

To find the smallest values after excluding values less than 0 in z, add the following code to the above snippet −

z<-rnorm(20,1,0.5)
df3<-data.frame(z)
min(df3[df3$z>0,1])

Output

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

[1] 0.1325154

Updated on: 09-Nov-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements