Reputation: 1979
I'd like to remove the last character of a string if there is any letter at the end of it.
sample vector is:
string <- c("L_3_A_L_3_1b", "L_3_A_L_3_1e", "L_3_A_L_3_1h", "RL_3_C_RL_3_9", "SL_3_A_SL_3_2")
I'd like to drop the last letter as:
> string
[1] "L_3_A_L_3_1" "L_3_A_L_3_1" "L_3_A_L_3_1" "RL_3_C_RL_3_9" "SL_3_A_SL_3_2"
ANy thoughts? Thanks!
Upvotes: 1
Views: 419
Reputation: 887961
We can specify the letters ([A-Za-z]
) specifically (as the OP's post is if there is any letter at the end of it
) to match at the end ($
) of the string and replace with blank (""
)
sub("[A-Za-z]$", "", string)
#[1] "L_3_A_L_3_1" "L_3_A_L_3_1" "L_3_A_L_3_1"
#[4] "RL_3_C_RL_3_9" "SL_3_A_SL_3_2"
Or use trimws
trimws(string, whitespace = '[A-Za-z]', which = 'right')
#[1] "L_3_A_L_3_1" "L_3_A_L_3_1" "L_3_A_L_3_1" "RL_3_C_RL_3_9" "SL_3_A_SL_3_2"
Upvotes: 2
Reputation: 1250
Try this:
library(stringr)
str_remove(string,"[a-zA-Z]$")
Upvotes: 2
Reputation: 21440
You can use the negative character class \\D
, which matches anything that is not a digit:
sub("\\D$", "", string)
[1] "L_3_A_L_3_1" "L_3_A_L_3_1" "L_3_A_L_3_1" "RL_3_C_RL_3_9" "SL_3_A_SL_3_2"
Upvotes: 2