jeudi 17 janvier 2019

str_sub returning NA with ifelse in R

I'm attempting to remove the last letter in a data frame if it matches 'Z' or 'Q'.

The data frame:

PlayerName    Score
'JohnQ'         75
'Robert'        80
'AlbertZ'       67
'JeffQ'         88

Code:

Remove 'Z' or 'Q' if last letter of string

data <- data %>% mutate(PlayerName = ifelse(stri_sub(data$PlayerName, -1) == 'Q'|
                                                stri_sub(data$PlayerName, -1) == 'Z', 
                                                str_sub(data$PlayerName, end=-2), 
                                                data$PlayerName))

When I run this code, I get:

PlayerName    Score
'NA'          75
'Robert'      80
'NA'          67
'NA'          88

No idea why this is happening, I the code str_sub(data$PlayerName, end=-2) returns the correct information when I use it outside of the ifelse function.

Aucun commentaire:

Enregistrer un commentaire