I have this vector:
data <- structure(1:5, .Label = c("AVE_prQD_AFR_p10", "PER_prVD_DSR_p9", "PA_prSX_AR_p8", 
"prAV_AES_p7", "prGR_AXXR_p6", "prQW_AWAR_p5"), class = "factor")
  V1
1 "AVE_prQD_AFR_p10"
2 "PER_prVD_DSR_p9"
3 "PA_prS_X_AR_p8"
4 "prAV_AES_p7"
5 "prGR_AXXR_p6"
I'm trying to extract the latest characters to the right, specifically from the latest _ to the end of the string. I don't know how many _ are in each string, but I do know that there always will be at least one, and always will be one _ before the part of the string I need. To give you an example:
"any_random_string_0" # "0" is the string I need
"any_random_string_f20" # "f20" is the string I need
"any_random_string_p3" # "p3" is the string I need
As you could infer from the example above, the last part of the string will always start with _, followed by a p, f or 0, and then will end the string with a number from 1 to 99" (except if its 0):
"_" + "f" or "p" or "0" + "1" to "99"
There is NEVER gonna be something after the number. Hence, the full string ends with the string I need. So, looking for a solution I was trying to find (unsuccessfully) some function that search _ from the right.
Plus, I need to transform that string given these conditions:
- If the string has p, multiply the number by-1
- If the string has f, the number is positive
- If the string is _0, give it0.
This is my attempt, it works, but only with a fixed position of _ and with a number from 0 to 9.
function(some_vector_string){
  result <- stringr::str_sub(some_vector_string, -2,-2) %>% 
    {ifelse(. == "p",
            as.numeric(stringr::str_sub(some_vector_string, -1,-1))*-1,
            ifelse(. == "f",
                   as.numeric(stringr::str_sub(some_vector_string, -1,-1))*1,
                   ifelse(.=="_", 0, -100)))}
  return(result)
}
 
     
     
     
     
    