Example data:
example <- data.frame(matrix(NA, ncol=4, nrow=4))
names(example) <- c("reason_code", "d_01", "d_02", "d_03")
example$reason_code <- c("d_01, d_03", "d_01", "d_02", "d_02, d_03")
Giving:
reason_code d_01 d_02 d_03
1 d_01, d_03 NA NA NA
2 d_01 NA NA NA
3 d_02 NA NA NA
4 d_02, d_03 NA NA NA
The reason_code
column sometimes contains more than one reason code. I have created a separate column for each reason code and want to search for the column name in the reason_code
column and return a logical to indicate its presence, as in the following:
library(stringr)
example$d_01 <- str_detect(example$reason_code, "d_01")
Giving:
reason_code d_01 d_02 d_03
1 d_01, d_03 TRUE NA NA
2 d_01 TRUE NA NA
3 d_02 FALSE NA NA
4 d_02, d_03 FALSE NA NA
My real data has many more reason codes and as such would like to know how I would use a function to iterate over each of the columns, searching for the column name in each row of the reason_code
column and returning TRUE
or FALSE
before moving on to the next column?
P.s. I am told by the stackoverflow A.I. that my title is likely to get downvoted or closed, however I have no idea how to explain what I'm after succinctly and accurately. I hope the example makes it clear.