-1

I need an additional solution to the previous question/answer Move characters from beginning of column name to end of column name

I have a dataset where column names have two parts divided by _ e.g.

pal036a_lon 
pal036a_lat 
pal036a_elevation

I would like to convert the prefixes into suffixes so that it becomes:

lon_pal036a 
lat_pal036a 
elevation_pal036a

The answer to the previous question

names(df) <- sub("([a-z])_([a-z]+)", "\\2_\\1", names(df))

does not work for numbers within the prefixes.

markus
  • 25,843
  • 5
  • 39
  • 58
  • I think in general I would opt to use a negated character class in such case like `([^_]+)_([^_]+)` for example, or if these column names are typically just word-characters: `(\w+)_(\w+)` – JvdV Feb 16 '21 at 08:52

2 Answers2

2

Assuming your names have a single _. You could also you strsplit():

sapply(strsplit(names(df), '_'), function(x) paste(rev(x), collapse = '_'))

If you have more than one you could modify the above as suggested by jay.sf:

sapply(strsplit(x, "_"), function(x) paste(c(x[length(x)], x[-length(x)]), collapse="_"))
s_baldur
  • 29,441
  • 4
  • 36
  • 69
1

You can include alphanumeric characters in the first group:

names(df) <- sub("([a-z0-9]+)_([a-z]+)", "\\2_\\1", names(df))

For example :

x <- c("pal036a_lon","pal036a_lat","pal036a_elevation")
sub("([a-z0-9]+)_([a-z]+)", "\\2_\\1",x)
#[1] "lon_pal036a"       "lat_pal036a"       "elevation_pal036a"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213