lundi 31 août 2020

If (no else)-sentences with substring in R

I have a df, I would like to substring the first letters for all columns in the screen_name column, except for the cell with the name 'frank'. All my attempts are ignored by R (substring is executed on all cells). Why?


df <- data.frame("screen_name" = c("august", "berit", "christopher", "david", "erica", "frank"), "rt_name" = c("berit", "august", "david", "erica", "frank", "christopher"))

#IF-sentence with '%!like%' 
'%!like%' <- function(x,y)!('%like%'(x,y))
df$screen_name<- if(df$screen_name %!like% ('frank')) {substr(df$screen_name, 1, 2)}

#IF-sentence with !=
df$screen_name<- if(df$screen_name != 'frank') {substr(df$screen_name, 1, 2)}

I am looking for solution that include %!like% or similar as the names in the df can vary and I am not always having an exact match.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire