How to find the minimum for each row based on few columns in an R data frame?

To find the minimum for each row based on few columns in an R data frame, we can use pmin function inside with function.

For example, if we have a data frame called df that contains five columns say x, y, z, a, and b then minimum for each row based on columns x, y, and b can be found by using the command given below −

with(df,pmin(x,y,b))

Example 1

Following snippet creates a sample data frame −

x1<-rnorm(20)
x2<-rnorm(20)
x3<-rnorm(20)
x4<-rnorm(20)
df1<-data.frame(x1,x2,x3,x4)
df1

The following dataframe is created −

      x1            x2          x3           x4
1  -0.11773107  -0.82035732  -0.28450601  -1.10704509
2  -1.01962604  -2.60294139   0.45711797   0.43207151
3   1.13500837  -1.14440016  -0.26626228  -0.73794240
4  -0.80790790  -1.14806291   0.35394025  -0.12112739
5  -0.06178105  -0.57400680  -0.66666658   1.09352761
6  -0.27553943  -1.36698799  -0.31081777   0.04752593
7   0.10584138  -1.34775886   0.17752275   0.38897313
8  -0.12614587  -0.03826633   0.70551865  -1.15621529
9   1.30759989  -0.23571489   0.38343949  -0.33398701
10  0.80694222   1.01968698   0.97463771  -0.47795594
11 -1.18169096  -0.03684450  -0.59514439  -1.21205644
12  0.43798192  -0.45043310  -0.42103633  -0.81786582
13  0.08569171  -0.21929358  -0.29929403   0.48033841
14  1.03432091  -0.66014884   0.40906268  -2.26329167
15 -1.90251190  -1.19862628   0.41706688  -0.44017107
16 -0.35222400   0.37808439  -0.68560797   0.36525694
17 -1.38445655   1.73951876   1.24614256  -2.23414164
18 -1.33440782   0.50000865   0.85680768   0.13643720
19 -1.29441749  -0.18851102  -0.69235928  -0.13695773
20  0.05258651  -0.10824434  -0.06976701   0.13541223

To find the minimum of each row for columns x2, x3, and x4, add the following code to the above snippet −

x1<-rnorm(20)
x2<-rnorm(20)
x3<-rnorm(20)
x4<-rnorm(20)
df1<-data.frame(x1,x2,x3,x4)
df2

Output

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

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

Updated on: 03-Nov-2021

2K+ Views