Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop over multiple character columns to derive a new variable

Could you please help me with a code in R. I want to derive a new variable available with values as Yes or No, however it need to check the character variables a1, a2, a3, a4 and whichever variable has a value as ‘yellow’ then available variable should be yes else no.

a1 <- c('orange','red') 
a2 <- c('red','yellow') 
a3 <- c('black','orange') 
a4 <- c('red','brown')

testa <- data.frame(a1,a2,a3,a4)

I want the available variable as below

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

dplyr

You may use rowwise and c_across:

testa %>% 
  rowwise() %>% 
  mutate(available = ifelse(any(c_across(a1:a4) == "yellow"), "yes", "no"))

  a1     a2     a3     a4    available
  <chr>  <chr>  <chr>  <chr> <chr>    
1 orange red    black  red   no       
2 red    yellow orange brown yes      

base R

Use apply:

testa$available <- apply(testa, 1, function(x) ifelse(any(x == "yellow"), "yes", "no"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading