How to find row minimum for an R data frame?


Data analysis is a difficult task because it has so much variation in terms of the smaller objectives of a big project. One of the smallest tasks could be finding the minimum value in each row contained in a data frame. For this purpose, we cam use apply function and pass the FUN argument as min so that we can get minimum values.

Consider the below data frame −

Example

 Live Demo

set.seed(101)
x1<-rpois(20,1)
x2<-rpois(20,2)
x3<-rpois(20,5)
df1<-data.frame(x1,x2,x3)
df1

Output

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

Creating a new column Min for minimum of each row −

Example

df1$Min<-apply(df1,1,FUN=min)
df1

Output

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

Let’s have a look at another example −

Example

 Live Demo

y1<-sample(0:9,20,replace=TRUE)
y2<-sample(0:9,20,replace=TRUE)
y3<-sample(0:9,20,replace=TRUE)
y4<-sample(0:9,20,replace=TRUE)
df2<-data.frame(y1,y2,y3,y4)
df2

Output

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

Creating a new column Minimum for minimum of each row −

Example

df2$Minimum<-apply(df2,1,FUN=min)
df2

Output

  y1 y2 y3 y4 Minimum
1  8  9  9  3 3
2  4  4  6  5 4
3  0  1  8  2 0
4  2  8  8  4 2
5  9  1  8  6 1
6  8  4  4  1 1
7  2  2  1  3 1
8  9  8  6  3 3
9  3  9  8  8 3
10 1  6  9  8 1
11 0  3  4  2 0
12 5  0 7 6 0
13 8  7  4 7 4
14 1  3  5 2 1
15 1  7  8 1 1
16 0  9  5 5 0
17 5  9  8 0 0
18 5  3  2 3 2
19 1  3  9 7 1
20 8  2  6 2 2

Updated on: 10-Oct-2020

798 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements