I have a vector of strings:
asdf <- c("a^sdf^", "asdf^^")
Now i want to remove the last element of both strings, but only if that last element is a ^, resulting in:
[1] "a^sdf" "asdf"
I tried:
function1 <- function(x){
while(any(substr(x, nchar(x) - 1 + 1, nchar(x)) == "^")){
x <- gsub(".{1}$", "", x)
}
return(x)
}
function1(asdf)
[1] "a^sd" "asdf"
As you can see the first string is reduced to more than ^ at the end. I tried experimenting with if conditions in combination to the while loop but it didn't work out. What is missing so that only the ^ gets removed?