I have issues with my code. What I'm doing is trying to match these titles like Miss or Mrs with the input from titanic$Name. However, this works hardcoded but when making a function, it doesn't feed into the loops. When I use the function, it doesn't work:
my_title(titanic$Name[2])
I get "other" as the return, when the return should've been "Mrs.". This means the code isn't running. I'm not sure where to fix the error, it looks fine to me and hardcoded works, so I think either my loops are wrong or the feeding into the function is wrong.
name_exp <- c("Miss.", "Mrs.", "Mr.", "Master.", "Dr.", "Rev.")
my_title <- function(x){
i <- 1
for(i in length(name_exp)){
full_name <- paste(name_exp[i])
name_check <- grepl(x, pattern=full_name)
if(name_check=="TRUE"){
nmatches <- gregexpr(pattern=full_name, text=x[name_check])
finalnames <- regmatches(x[[name_check]], nmatches)
return(finalnames)
}
else{
if(i==6 & name_check=="FALSE"){
return("Other")
}
else{
i <- i+1
}
}
}
}
my_title(titanic$Name[1])
Aucun commentaire:
Enregistrer un commentaire