IF TRUE then 变量名

IF TRUE then Variable name

我有一系列代表搜索结果的 TRUE 和 FALSE 变量,例如:Cellphones、Knifes、Money 等。我的目标是更改变量名称的 TRUE 值。请注意,我想对 15 个或更多变量执行此操作。

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       

base R中,一个选项是遍历逻辑行列的子集,根据逻辑向量得到第一个列名

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

如果我们想在每一列上单独执行此操作

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

-输出

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>