I have a list (L) with several form of AB variable (like AB_1, AB_1_1 ,...), can I have a subset of list with only the first column that matches AB form. List (L) and desired result as List (R) are as follow:
L1 = data.frame(AB_1 = c(1:4) , AB_1_1 = c(1:4) , C1 = c(1:4))
L2 = data.frame(AB_1_1 = c(1:4) , AB_2 = c(1:4), D = c(1:4) )
L=list(L1,L2)
R1 = data.frame(AB_1 = c(1:4) , C1 = c(1:4))
R2 = data.frame(AB_1_1 = c(1:4) , D = c(1:4))
R=list(R1,R2)
It is not the best answer, but it is a solution: First change the name of all columns start with AB... to AB, and then remove the duplicate column names for each data frame in list (L).
for (i in 1:length(L)){
colnames(L[[i]])[grepl('AB',colnames(L[[i]]))] <- 'AB'
L[[i]] <- L[[i]][ , !duplicated(colnames(L[[i]]))]
}