How to find the row minimum excluding zero in R data frame returning 0 if all 0?

R ProgrammingServer Side ProgrammingProgramming

To find the row minimum excluding zero in R data frame returning 0 if all 0, we can follow the below steps −

  • First of all, create a data frame.
  • Then, find the row minimum by excluding zero using if function with apply function.

Example1

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x1<-sample(c(0,1,5),20,replace=TRUE)
x2<-sample(c(0,10,20),20,replace=TRUE)
x3<-sample(c(0,5,10),20,replace=TRUE)
df1<-data.frame(x1,x2,x3)
df1

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

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

Find row minimum by excluding zero returning 0 if all 0

Using apply function with if else function to find the row minimum by excluding zero returning 0 if all 0 −

 Live Demo

x1<-sample(c(0,1,5),20,replace=TRUE)
x2<-sample(c(0,10,20),20,replace=TRUE)
x3<-sample(c(0,5,10),20,replace=TRUE)
df1<-data.frame(x1,x2,x3)
apply(df1,1,function(x) if(all(x==0)) 0 else min(x[x>0]))

Output

[1] 10 0 1 5 5 1 10 5 20 1 1 5 0 5 5 5 5 5 5 1

Example 2

Create the data frame

Let's create a data frame as shown below −

 Live Demo

y1<-sample(c(0,50),20,replace=TRUE)
y2<-sample(c(0,75),20,replace=TRUE)
y3<-sample(c(0,90),20,replace=TRUE)
df2<-data.frame(y1,y2,y3)
df2
   y1 y2 y3
1 50 75 90
2 0 5 0
3 0 75 0
4 50 0 90
5 50 0 90
6 0 0 0
7 0 75 90
8 50 75 0
9 0 75 90
10 50 0 0
11 0 0 0
12 50 0 0
13 0 0 0
14 0 0 90
15 50 75 90
16 50 75 0
17 50 75 90
18 50 75 0
19 0 75 90
20 50 0 90

Find row minimum by excluding zero returning 0 if all 0

Using apply function with if else function to find the row minimum by excluding zero returning 0 if all 0 −

 Live Demo

y1<-sample(c(0,50),20,replace=TRUE)
y2<-sample(c(0,75),20,replace=TRUE)
y3<-sample(c(0,90),20,replace=TRUE)
df2<-data.frame(y1,y2,y3)
apply(df2,1,function(x) if(all(x==0)) 0 else min(x[x>0]))

Output

[1] 50 75 75 50 50 0 75 50 75 50 0 50 0 90 50 50 50 50 75 50
raja
Published on 07-Aug-2021 09:31:59
Advertisements