How do I split a string by r into a delimiter and discard the last two elements?
I have a string split _
and I want to get rid of the last two items. For example, from A_B_C_D
I want to return A_B
, and from A_B_C_D_E
I want A_B_C
. I tried str_split_fixed
from stringr
:
my_string <- "A_B_C_D"
x <- str_split_fixed(my_string,"_",3)
but it returns "A" "B" "C_D"
instead "A_B" "C" "D"
, otherwise I could do head(x,-2)
to getA_B
Is there a better way than
paste(head(unlist(strsplit(my_string,"_")),-2),collapse="_")
source to share