How to create a column of first non-zero value in each row of an R data frame?

R ProgrammingServer Side ProgrammingProgramming

To create a column of first non-zero value in each row of an R data frame, we can follow the below steps −

  • First of all, create a data frame with some zero values.

  • Then, use apply function and a custom function to find the first non-zero in each row of the data frame.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-sample(0:2,25,replace=TRUE)
y<-sample(0:2,25,replace=TRUE)
z<-sample(0:2,25,replace=TRUE)
a<-sample(0:2,25,replace=TRUE)
df<-data.frame(x,y,z,a)
df

Output

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

   x y z a
1  1 0 2 0
2  1 0 0 1
3  0 0 1 0
4  2 0 0 2
5  0 1 1 2
6  0 1 0 1
7  2 1 2 2
8  0 1 1 2
9  1 0 0 2
10 1 0 1 0
11 1 0 0 0
12 0 2 1 0
13 0 0 1 2
14 1 1 0 1
15 1 0 2 1
16 1 1 1 1
17 1 1 1 1
18 2 0 2 1
19 1 0 2 0
20 0 2 2 0
21 0 0 2 2
22 1 0 2 0
23 0 2 1 0
24 1 1 1 0
25 1 0 2 0

Find the first non-zero in each row of the data frame

Using apply function and a custom function to find the first non-zero in each row of the data frame df as shown below −

x<-sample(0:2,25,replace=TRUE)
y<-sample(0:2,25,replace=TRUE)
z<-sample(0:2,25,replace=TRUE)
a<-sample(0:2,25,replace=TRUE)
df<-data.frame(x,y,z,a)
df$First_Non_zero<-apply(df,1, function(x) x[x !=0][1])
df

Output

   x y z a First_Non_zero
1  1 2 1 0 1
2  0 2 2 2 2
3  0 0 2 1 2
4  0 2 1 1 2
5  2 0 0 1 2
6  2 1 0 2 2
7  1 2 1 1 1
8  1 1 0 1 1
9  1 2 2 0 1
10 2 0 1 0 2
11 2 1 1 1 2
12 0 0 0 1 1
13 2 2 1 1 2
14 0 1 1 1 1
15 1 1 1 1 1
16 2 1 0 1 2
17 1 0 1 0 1
18 1 2 1 1 1
19 0 2 1 1 2
20 0 1 1 2 1
21 0 1 2 0 1
22 1 0 2 0 1
23 1 1 1 0 1
24 0 0 2 0 2
25 2 2 1 2 2
raja
Updated on 12-Nov-2021 05:35:13

Advertisements