Home > OS >  IF TRUE then Variable name
IF TRUE then Variable name

Time:03-02

I have a series of TRUE and FALSE variables representing search findings, ex: Cellphones, Knifes, Money, etc. My goal is to change the values TRUE for the name of the variable. Note that I would like to do this for 15 or more variables.

df <- data.frame(cellphone = c(TRUE, TRUE, FALSE, TRUE, FALSE),
                 money = c(FALSE, FALSE, FALSE, TRUE, FALSE),
                 knife = c(TRUE,TRUE,FALSE, FALSE, FALSE),
                 whatIneed = c("cellphone", "cellphone", "", "cellphone",""))

  cellphone money knife whatIneed
1      TRUE FALSE  TRUE cellphone
2      TRUE FALSE  TRUE cellphone
3     FALSE FALSE FALSE          
4      TRUE  TRUE FALSE cellphone
5     FALSE FALSE FALSE       

CodePudding user response:

In base R, an option is to loop over the subset of columns that are logical rowwise, get the first column name based on the logical vector

df$whatIneed <- apply(df[1:3], 1, function(x) names(x)[x][1])
df$whatIneed
[1] "cellphone" "cellphone" NA          "cellphone" NA     

If we want to do this individually on each column

library(dplyr)
df %>%
    mutate(across(where(is.logical),
      ~ case_when(.x ~ cur_column()), .names = "{.col}_name"))

-output

cellphone money knife whatIneed cellphone_name money_name knife_name
1      TRUE FALSE  TRUE cellphone      cellphone       <NA>      knife
2      TRUE FALSE  TRUE cellphone      cellphone       <NA>      knife
3     FALSE FALSE FALSE                     <NA>       <NA>       <NA>
4      TRUE  TRUE FALSE cellphone      cellphone      money       <NA>
5     FALSE FALSE FALSE                     <NA>       <NA>       <NA>
  • Related