Search code examples
rdplyr

Extract column name depending on a specific value in dataframe


I have the following data:

my_data <- tribble(
  ~item1, ~item2,
  "car", "ferrari",
  "house", "3 bed",
  NA, "3"
)

I am trying to extract the name of the column, in which "house" exists

I have tried:

my_data %>%
mutate(across(everything(), ~str_detect(.x , "house")))

which returns:

# A tibble: 3 × 2
  item1 item2
  <lgl> <lgl>
1 FALSE FALSE
2 TRUE  FALSE
3 NA    FALSE

And this is where I'm stuck, trying to extract the column "item1", I have tried using the function any() but that condenses the whole thing to TRUE.

Looking for a dplyr/purrr solution please. Thanks.

Edit: There isn't a need to treat my question in such a broad brush way and just close it. The 1st "similar" question doesn't use dplyr and subsets the data, which is not what I have asked. And I appreciate that the 2nd "similar" does apply the same function, however doesn't return for the name of the column as a character like I have asked... i.e. I wouldn't have known you can apply names straight after. And there is also a discussion about whether where is needed, which none of the other questions discuss.


Solution

  • Using select(where()):

    library(dplyr)
    
    my_data %>%
      select(where(\(x) "house" %in% x)) %>%
      names()
    # "item1"