Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove first two characters for all column names in a data frame in R

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

like image 756
user36176 Avatar asked Dec 02 '15 16:12

user36176


2 Answers

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
like image 138
maccruiskeen Avatar answered Oct 22 '22 08:10

maccruiskeen


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
like image 20
Little Bee Avatar answered Oct 22 '22 09:10

Little Bee