How to find the column index in an R data frame that matches a condition?


To find the column index that matches a condition, we can use apply function. This condition could be values in columns greater than something, less than something, equal to something, or any other condition for numerical variables. For example, if we want to check which columns of data df contains value in rows greater than 5 then we can use the command apply(df,1, function(x) which(x>5)).

Consider the below data frame −

Example

 Live Demo

x1<-rnorm(20,2,0.05)
x2<-rnorm(20,2,0.65)
df1<-data.frame(x1,x2)
df1

Output

      x1      x2
1  2.083832  3.238437
2  1.999989  2.409343
3  1.908010  2.088710
4  1.914835  2.421812
5  2.080797  1.705331
6  1.977896  1.337907
7  1.987243  2.687881
8  2.002822  2.850734
9  1.932333  2.470400
10 1.955817  1.652495
11 2.085809  1.490701
12 1.986614  1.733392
13 1.975024  1.742006
14 1.983986  2.441801
15 1.991714  2.450637
16 1.947738  1.105244
17 2.052789  2.020752
18 1.989781  1.438219
19 2.023067  1.615221
20 2.086341  3.046352

Checking which columns of df1 have value greater than 1.5 for each row −

apply(df1,1, function(x) which(x>1.5))

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

Updated on: 06-Feb-2021

836 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements