create variable multuple values r code example

Example: create variable multuple values r

library(tidyverse)

#Make an example dataset



allwords <- c("apple", "banana", "carrot", "cucumber", "lettuce", "tomato")

ha <- tibble(new_drug_1=sample(allwords, 200, replace=TRUE),
             new_drug_2=sample(allwords, 200, replace=TRUE),
             new_drug_3=sample(allwords, 200, replace=TRUE),
             new_drug_4=sample(allwords, 200, replace=TRUE),
             new_drug_5=sample(allwords, 200, replace=TRUE))

ha
#> # A tibble: 200 x 5
#>    new_drug_1 new_drug_2 new_drug_3 new_drug_4 new_drug_5
#>    <chr>      <chr>      <chr>      <chr>      <chr>     
#>  1 carrot     banana     banana     banana     tomato    
#>  2 tomato     lettuce    apple      carrot     banana    
#>  3 carrot     cucumber   lettuce    tomato     cucumber  
#>  4 lettuce    carrot     banana     carrot     apple     
#>  5 banana     cucumber   banana     apple      cucumber  
#>  6 apple      apple      cucumber   banana     banana    
#>  7 carrot     cucumber   lettuce    cucumber   apple     
#>  8 lettuce    cucumber   apple      carrot     cucumber  
#>  9 apple      lettuce    cucumber   lettuce    cucumber  
#> 10 lettuce    tomato     apple      lettuce    tomato    
#> # ... with 190 more rows

#This would be a vector of your 6 words you are searching for
#In my case, it just has 2 words
wordlist <- c("apple", "banana") 

ha %>%
  mutate(ha_rescue=if_else(
    new_drug_1 %in% wordlist | new_drug_2 %in% wordlist | new_drug_3 %in% wordlist |new_drug_4 %in% wordlist |new_drug_5 %in% wordlist,
    "yes",
    "no"
  ))
#> # A tibble: 200 x 6
#>    new_drug_1 new_drug_2 new_drug_3 new_drug_4 new_drug_5 ha_rescue
#>    <chr>      <chr>      <chr>      <chr>      <chr>      <chr>    
#>  1 carrot     banana     banana     banana     tomato     yes      
#>  2 tomato     lettuce    apple      carrot     banana     yes      
#>  3 carrot     cucumber   lettuce    tomato     cucumber   no       
#>  4 lettuce    carrot     banana     carrot     apple      yes      
#>  5 banana     cucumber   banana     apple      cucumber   yes      
#>  6 apple      apple      cucumber   banana     banana     yes      
#>  7 carrot     cucumber   lettuce    cucumber   apple      yes      
#>  8 lettuce    cucumber   apple      carrot     cucumber   yes      
#>  9 apple      lettuce    cucumber   lettuce    cucumber   yes      
#> 10 lettuce    tomato     apple      lettuce    tomato     yes      
#> # ... with 190 more rows

Tags:

R Example