string 删除 R 中数据框中所有列名的前两个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34047552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:28:23  来源:igfitidea点击:

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

rstringsubstring

提问by user36176

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

我知道字符串函数可以在行上使用,但我找不到列名的东西

回答by maccruiskeen

Use substring()

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

回答by Little Bee

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

指定我们要保留的字符,例如将字符 1 到 5 保留在 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