Find the column and row names in the R data frame based on condition.

R ProgrammingServer Side ProgrammingProgramming

To find the column names and row names in an R data frame based on a condition, we can use row.names and colnames function. The condition for which we want to find the row names and column names can be defined inside these functions as shown in the below Examples.

Example 1

Following snippet creates a sample data frame −

x1<-rpois(20,1)
x2<-rpois(20,8)
x3<-rpois(20,20)
df1<-data.frame(x1,x2,x3)
df1

The following dataframe is created

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

To find which rows has value 17 in it on the above created data frame, add the following code to the above snippet −

x1<-rpois(20,1)
x2<-rpois(20,8)
x3<-rpois(20,20)
df1<-data.frame(x1,x2,x3)
row.names(df1[which(df1==17,arr.ind=T)[,1],] )

Output

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

[1] "5" "19"

To find which columns has value 17 in it on the above created data frame, add the following code to the above snippet −

x1<-rpois(20,1)
x2<-rpois(20,8)
x3<-rpois(20,20)
df1<-data.frame(x1,x2,x3)
colnames(df1)[apply(df1, 2, function(x) any(x==17))]

Output

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

[1] "x3"

Example 2

Following snippet creates a sample data frame −

y1<-sample(1:100,20)
y2<-sample(1:100,20)
y3<-sample(1:100,20)
df2<-data.frame(y1,y2,y3)
df2

The following dataframe is created

   y1 y2 y3
1  75 52 32
2  37  5 46
3  43 31 60
4 100 30 11
5  28 18 79
6  31 80 53
7   8 85 49
8  62 38 56
9  48 82 15
10 97 48 69
11 69 25 40
12 12 92 21
13 77 55 26
14 39 95 63
15 82 61 75
16 98 40 14
17 61 78 22
18 93 63 58
19 10 21 17
20 2 68 83

To find which rows has value 92 in it on the above created data frame, add the following code to the above snippet −

y1<-sample(1:100,20)
y2<-sample(1:100,20)
y3<-sample(1:100,20)
df2<-data.frame(y1,y2,y3)
row.names(df2[which(df2==92,arr.ind=T)[,1],] )

Output

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

[1] "12"

To find which columns have value 92 in it on the above created data frame, add the following code to the above snippet −

y1<-sample(1:100,20)
y2<-sample(1:100,20)
y3<-sample(1:100,20)
df2<-data.frame(y1,y2,y3)
colnames(df2)[apply(df2, 2, function(x) any(x==92))]

Output

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

[1] "y2"
raja
Published on 01-Nov-2021 08:28:55
Advertisements