10

Is there a way to remove character strings by position from all column names in a data frame

for eg if i have column names like:

ab_sales1 kj_sales2 lm_sales3 .....pk_sales100
10         34         64      .....  288

I would like my output column names to be something like

  sales1 sales2 sales3 .....sales100
    10     34    64     .... 288

I know string functions can be used on rows but I could not find something for column names

3
  • Try colnames(df)<-sub("^[^_]*_","",colnames(df))
    – nicola
    Dec 2, 2015 at 16:18
  • 2
    Did you look at ?substr and ?colnames?
    – talat
    Dec 2, 2015 at 16:18
  • I was unaware that substring could be used on column names!
    – user36176
    Dec 2, 2015 at 16:41

2 Answers 2

23

Use substring()

df <- data.frame(ab_sales1   = rnorm(6),
                 kj_sales2   = rnorm(6),
                 lm_sales3   = rnorm(6),
                 pk_sales100 = rnorm(6))
names(df) <- substring(names(df), 4)

This gives:

      sales1     sales2     sales3    sales100
1  0.9486393  0.4727444 -1.5982694  0.01102933
2  0.2980252 -0.7979390 -2.2574233 -0.37381571
3 -0.5788511 -0.4873044  2.1668715 -0.26525840
4 -1.0711035  1.0311850  0.3495215 -0.58936920
5  0.2432300  1.7801097 -1.1982068  0.14810607
6  1.6965152  0.9655296 -1.1000140 -1.02301506
6

to specify the characters we want to keep, for example keeping character 1 to 5 in colnames

names(df) <- substring(names(df),1,5)

this gives

       ab_sa      kj_sa      lm_sa       pk_sa
1  0.4766499 -0.1179655  0.7169561 -0.49368959
2 -1.5783553 -0.7481989  1.1739097  0.21988629
3 -1.2270336  2.4848512  0.3982539  1.19795271
4 -0.5443994  0.1170061  0.6622701 -0.48468645
5 -0.5591005  1.9600350  0.3473387  0.78863634
6 -0.9692961 -1.0195691 -0.5949841 -0.08180169
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.