How to create a column of first non-zero value in each row of a data.table object in R?

R ProgrammingServer Side ProgrammingProgramming

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

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

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

Example

Create the data.table object

Let’s create a data.table object as shown below −

library(data.table)
v1<-sample(0:5,25,replace=TRUE)
v2<-sample(0:5,25,replace=TRUE)
v3<-sample(0:5,25,replace=TRUE)
DT<-data.table(v1,v2,v3)
DT

Output

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

   v1 v2 v3
1:  0  2 4
2:  0  4 1
3:  4  1 2
4:  2  5 0
5:  5  3 4
6:  1  1 5
7:  5  3 0
8:  5  0 1
9:  5  3 4
10: 0  3 2
11: 5  3 2
12: 5  4 4
13: 4  1 2
14: 5  1 2
15: 5  1 5
16: 4  3 1
17: 2  1 5
18: 2  4 2
19: 4  0 0
20: 3  1 2
21: 0  4 5
22: 5  0 0
23: 5  2 5
24: 5  1 1
25: 1  5 5
   v1 v2 v3

Find the first non-zero in each row of the data.table object

Using apply function and a custom function to find the first non-zero in each row of the data.table object DT as shown below −

library(data.table)
v1<-sample(0:5,25,replace=TRUE)
v2<-sample(0:5,25,replace=TRUE)
v3<-sample(0:5,25,replace=TRUE)
DT<-data.table(v1,v2,v3)
DT$First_Non_zero<-apply(DT,1, function(x) x[x !=0][1])
DT

Output

   v1 v2 v3 First_Non_zero
1:  0 2  4  2
2:  0 4  1  4
3:  4 1  2  4
4:  2 5  0  2
5:  5 3  4  5
6:  1 1  5  1
7:  5 3  0  5
8:  5 0  1  5
9:  5 3  4  5
10: 0 3  2  3
11: 5 3  2  5
12: 5 4  4  5
13: 4 1  2  4
14: 5 1  2  5
15: 5 1  5  5
16: 4 3  1  4
17: 2 1  5  2
18: 2 4  2  2
19: 4 0  0  4
20: 3 1  2  3
21: 0 4  5  4
22: 5 0  0  5
23: 5 2  5  5
24: 5 1   1 5
25: 1 5  5  1
  v1 v2 v3 First_Non_zero
raja
Updated on 12-Nov-2021 06:44:54

Advertisements