Reputation: 11
string extraction using a defined function
I wrote a code to extract a portion of the string but the code doesn't run. It doesn't give me any error either. Please tell what am I missing. I am trying pass an input argument named address and return a value
notes_address <- function(address) {
address1 <- tolower(address)
if(grepl("sent to.*. for del ", address1)) {
address1 <- gsub(".*?sent to(.*?)(for del.*|$)", "\\1", )
}
else {address1 <- NA}
return(address1)
}
For example, if a <- "when you go sent to backstreet ave del to Mrs Kenwood"
, I expect the output to be: "backstreet ave"
Upvotes: 0
Views: 358
Reputation: 5673
There isn't any for
characters in your example string, so your function return NA because in the else
part of your function you return NA. You can't have the expected output here. To have the expected output with your function:
notes_address <- function(address) {
address1 <- tolower(address)
if(grepl("sent to.*. del ", address1)) {
address1 <- gsub(".*?sent to(.*?)(del.*|$)", "\\1", address1)
}
else {address1 <- NA}
return(address1)
}
a <- "when you go sent to backstreet ave del to Mrs Kenwood"
notes_address(a)
[1] " backstreet ave "
But I am not sure it is what you want. If it is, I would advise you to use the stringr
library with the str_extract
function:
library(stringr)
str_extract(a,"(?<=sent to ).+(?= del)")
Gives the same output as your function
Upvotes: 1