Pattern matching and removing from the name colnames(countdata) = gsub("Aligned.sortedByCoord.out.bam_rem.bam", "", colnames(countdata))
colnames(countdata)
dput(colnames(countdata))
    c("BAF60A_KD_1_S13", "BAF60A_KD_2_S14", "BAF60A_RA_1_S17", "BAF60A_RA_2_S18", 
    "BAF60A_VD3_1_S15", "BAF60A_VD3_2_S16", "BAF60C_KD_1_UI_S1", 
    "BAF60C_KD_2_UI_S2", "BAF60C_KD_RA_1_S11", "BAF60C_KD_RA_2_S12", 
    "BAF60C_KD_VD3_1_S9", "BAF60C_KD_VD3_2_S10", "VC_1_UI_S3", "VC_2_UI_S4", 
    "VC_RA1_S5", "VC_RA_2_S6", "VC_VD3_1_S7", "VC_VD3_2_S8")


After removing the above pattern I want to remove this part from each of the colnames _S[anynumber] so that I can end up like this as an example  BAF60A_KD_1 but not sure how to make that pattern and match the same and remove or replace it with empty space. I tried as below which ends up like all the digits are removed.

colnames(countdata) = gsub("[[:digit:]_S]", "", colnames(countdata))

colnames(countdata)

c("BAFAKD", "BAFAKD", "BAFARA", "BAFARA", "BAFAVD", "BAFAVD", 
"BAFCKDUI", "BAFCKDUI", "BAFCKDRA", "BAFCKDRA", "BAFCKDVD", "BAFCKDVD", 
"VCUI", "VCUI", "VCRA", "VCRA", "VCVD", "VCVD")    


Any suggestion would be helpful
Without regex, split on "_", drop last item, then paste it back again:

sapply(strsplit(x, "_"), function(i) paste(head(i, -1), collapse = "_"))


Or with regex (stealing the code from tools::file_path_sans_ext function which is used to drop file extensions):

sub("([^_]+)\\_[[:alnum:]]+$", "\\1", x)

# [1] "BAF60A_KD_1"     "BAF60A_KD_2"     "BAF60A_RA_1"     "BAF60A_RA_2"     "BAF60A_VD3_1"    "BAF60A_VD3_2"   
# [7] "BAF60C_KD_1_UI"  "BAF60C_KD_2_UI"  "BAF60C_KD_RA_1"  "BAF60C_KD_RA_2"  "BAF60C_KD_VD3_1" "BAF60C_KD_VD3_2"
# [13] "VC_1_UI"         "VC_2_UI"         "VC_RA1"          "VC_RA_2"         "VC_VD3_1"        "VC_VD3_2"