R - Replace value with the name of its respective column if the Value is TRUE

rstudio

#1

I have a data frame:

Prod_Des MF240 MF2604H MF2605 MF2605H MF2606H
1 A FALSE TRUE FALSE FALSE FALSE
2 B FALSE FALSE TRUE FALSE FALSE
3 C TRUE FALSE FALSE FALSE FALSE
4 D FALSE FALSE TRUE FALSE FALSE
5 E FALSE FALSE FALSE TRUE FALSE
6 F FALSE FALSE FALSE FALSE TRUE
7 G FALSE FALSE TRUE FALSE FALSE
8 H FALSE FALSE FALSE TRUE FALSE

I'm trying to replace the "true" character values with the respective column name (e.g. "MF2606H"). This is my desired output:

Prod_Des MF240 MF2604H MF2605 MF2605H MF2606H
1 A FALSE MF2604H FALSE FALSE FALSE
2 B FALSE FALSE MF2605 FALSE FALSE
3 C MF240 FALSE FALSE FALSE FALSE
4 D FALSE FALSE MF2605 FALSE FALSE
5 E FALSE FALSE FALSE MF2605H FALSE
6 F FALSE FALSE FALSE FALSE MF2606H
7 G FALSE FALSE MF2605 FALSE FALSE
8 H FALSE FALSE FALSE MF2605H FALSE

I am trying this code:

temp=which(df== "TRUE",arr.ind = T)

df[temp]t=colnames(df)[temp[,2]]

But this code is replacing the respective values with NA. Any other alternatives??


#2

Hello abhilash!

Hope you are having a good day. I enjoyed your question! Here are some resources if you want to dig a little deeper into the concepts I'm using:

Iteration: http://r4ds.had.co.nz/iteration.html
Strings: http://r4ds.had.co.nz/strings.html

library(tidyverse)
my_tibble <- tibble(
  Prod_Des = c("A", "B", "C", "D", "E", "F", "G", "H"),
  MF240 = c(rep(FALSE, 2), TRUE, rep(FALSE, 5)),
  MF2604H = c(TRUE, rep(FALSE, 7)),
  MF2605 = c(FALSE, TRUE, FALSE, TRUE, rep(FALSE, 2), TRUE, FALSE),
  MF2605H = c(rep(FALSE, 4), TRUE, rep(FALSE, 2), TRUE),
  MF2606H = c(rep(FALSE, 5), TRUE, rep(FALSE, 2))
)

for (i in 1:length(my_tibble)) {
    my_tibble[[i]] <- str_replace(my_tibble[[i]], "TRUE", colnames(my_tibble)[i])
}

I also included the code to make your tibble/data frame so that others could easily find other solutions. Have a good one

Best,
fran


#3

Thanks alot Fran-ny.