I have a data frame formatted like so:
val1 = c(.35, .36, .35, .22, .27, .25) val2 = c(.35, .35, .37, .40, .42, .46) val3 = c(.88, .9, .87, .35, .35, .36) val4 = c(.9, .91, .82, .36, .36, .36) df = data.frame (val1, val2, val3, val4) colnames(df)[1] = "group 1_31" colnames(df)[2] = "group 1_32" colnames(df)[3] = "group 2_32" colnames(df)[4] = "group 10_310" I know these column names are less than ideal, but unfortunately they are automatically supplied by the program I'm running. I'd like to rename each column, such that group a_bc becomes bca, like so:
colnames(df)[1] = "311" colnames(df)[2] = "321" colnames(df)[3] = "322" colnames(df)[4] = "31010" I know I can get rid of "group" by doing:
colnames(df)=sub("group ","",colnames(df)) but that still leaves me with "1_31", "1_32", etc.
Is there a way to automatically convert a_bc to bca across all columns names (I have 55 that need this conversion)?
I've read Rename Dataframe Column Names in R using Previous Column Name and Regex Pattern but I think my case is different because I need to reorder the existing column name, not just cut them off at a specific position.