vendredi 5 juillet 2019

Ifelse statement checked against a list

Trying to match a column against a list and return 'match' if there is a match using ifelse

It feels like it should look like this:

df <- as_tibble(1:10)
df1 <- c(5,6,7,8,9,10)
df$b <- ifelse(df$value == df1, 'match', NA)

Warning message:
In df$value == df1 :
  longer object length is not a multiple of shorter object length

I got closer with this try:

> df$b <- ifelse(grepl(df1,df$value), 'match', NA)


Warning message:
In grepl(df1, df$value) :
  argument 'pattern' has length > 1 and only the first element will be used

 value b    
   <int> <chr>
 1     1 NA   
 2     2 NA   
 3     3 NA   
 4     4 NA   
 5     5 match
 6     6 NA   
 7     7 NA   
 8     8 NA   
 9     9 NA   
10    10 NA

What I am trying to get is:

value b 
   <int> <chr>
 1     1 NA   
 2     2 NA   
 3     3 NA   
 4     4 NA   
 5     5 match
 6     6 match   
 7     7 match   
 8     8 match   
 9     9 match   
10    10 match  

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire