Ssong
Ssong

Reputation: 452

How to rename the specific pattern in the column name?

I'd like to rename a value with a specific pattern in the column name.
For example,

ex_before<-data.frame(A1B..123.=c('a', 'b', 'c'), 
               BCD43..24.=c('d', 'e', 'f'), 
               Q2E4W..532.=c(1,4,2),
               OI95J8..934.=c(9,3,9))
ex_before
  A1B..123. BCD43..24. Q2E4W..532. OI95J8..934.
1        a        d         1         9
2        b        e         4         3
3        c        f         2         9

ex_after<-data.frame('123'=c('a', 'b', 'c'), 
               '24'=c('d', 'e', 'f'), 
               '532'=c(1,4,2),
               '934'=c(9,3,9))
names(ex_after)<-gsub(x=names(ex_after), pattern="X", replacement="")
ex_after
  123 24 532 934
1   a  d   1   9
2   b  e   4   3
3   c  f   2   9

I tried the stupid method like below, but I guess that there must be a more efficient method.

names(ex_before)<-gsub(x=names(ex_before), pattern="\\w+\\..", replacement="")
names(ex_before)<-gsub(x=names(ex_before), pattern="\\.", replacement="")

ex_before
  123 24 532 934
1   a  d   1   9
2   b  e   4   3
3   c  f   2   9

Can anyone suggest other approach?

Upvotes: 2

Views: 402

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

How about this?

names(ex_before) <- sub('.*\\.(\\d+)\\.$', '\\1', names(ex_before))
ex_before

#  123 24 532 934
#1   a  d   1   9
#2   b  e   4   3
#3   c  f   2   9

This basically extracts the number which are between periods (".").

Upvotes: 3

Related Questions