DeduciveR
DeduciveR

Reputation: 1702

subset columns in a data frame by a row value using select in dplyr

I'm looking to subset a data frame by the entry in the first row. For example:

col1 <- c("blue", 2, "small")
col2 <- c("red", 4, "large")
col3 <- c("green", 3, "medium")

df <- data.frame(col1, col2, col3)

... I'd like to subset df to just col2 based on the first entry being "red". If there were two columns that matched that criteria, eg:

col1 <- c("blue", 2, "small")
col2 <- c("red", 4, "large")
col3 <- c("green", 3, "medium")
col4 <- c("red", 5, "small")

df <- data.frame(col1, col2, col3, col4)

... cols 2 & 4 should be returned.

I've looked at this answer to my question - the answer's 5 years' old so I'm hoping there's a far more elegant way by using select in dplyr.

Thanks.

Upvotes: 0

Views: 220

Answers (1)

jasbner
jasbner

Reputation: 2283

Could just select them without dplyr.

df <- data.frame(col1, col2, col3, col4)    
df[,df[1,] == "red", drop = F]
#    col2  col4
# 1   red   red
# 2     4     5
# 3 large small

Upvotes: 1

Related Questions