I have a string separated by _ and I want to get rid of the last two elements. 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 have 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 of "A_B" "C" "D", otherwise I could have done head(x,-2) to get A_B
Is there a better way than
paste(head(unlist(strsplit(my_string,"_")),-2),collapse="_")
How about using a regex:
Where the number
2is the length you want to drop.