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

做~自己de王妃 提交于 2020-01-12 09:52:09

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/34047552/remove-first-two-characters-for-all-column-names-in-a-data-frame-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!