Adam Amin
Adam Amin

Reputation: 1456

Finding columns that contain values based on another column

I have the following data frame:

Step    1   2   3
1       5   10  6
2       5   11  5
3       5   13  9
4       5   15  10
5       13  18  10
6       15  20  10
7       17  23  10
8       19  25  10
9       21  27  13
10      23  30  7

I would like to retrieve the columns that satisfy one of the following conditions: if step 1 = step 4 or step 4 = step 8. In this case, column 1 and 3 should be retrieved. Column 1 because the value at Step 1 = value at step 4 (i.e., 5), and for column 3, the value at step 4 = value at step 8 (i.e., 10).

I don't know how to do that in R. Can someone help me please?

Upvotes: 2

Views: 49

Answers (1)

Darren Tsai
Darren Tsai

Reputation: 35554

You can get the column indices by the following code:

df[1, -1] == df[4, -1] | df[4, -1] == df[8, -1]

#     X1    X2   X3
# 1 TRUE FALSE TRUE

# data
df <- structure(list(Step = 1:10, X1 = c(5L, 5L, 5L, 5L, 13L, 15L, 
17L, 19L, 21L, 23L), X2 = c(10L, 11L, 13L, 15L, 18L, 20L, 23L, 
25L, 27L, 30L), X3 = c(6L, 5L, 9L, 10L, 10L, 10L, 10L, 10L, 13L, 
7L)), class = "data.frame", row.names = c(NA, -10L))

Upvotes: 2

Related Questions