删除列名中的字符 [英] to delete characters in column names

查看:46
本文介绍了删除列名中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有以下数据

Ind var1_1 var2_2 var3_1 var4_2.......var100_1
 1   0      0       2      1             0
 2   2      0       1      0             2

我想重命名后面没有两个字符的列,如下

And I want to rename the columns without the two characters at the back as follows

Ind var1 var2 var3 var4.......var100
 1   0     0    2    1           0
 2   2     0    1    0           2

推荐答案

我们可以使用sub.我们将模式 _ 后跟一个或多个数字 (\\d+) 匹配到字符串的末尾 ($) 并替换为 <代码>''.

We can use sub. We match the pattern _ followed by one or more digits (\\d+) to the end ($) of the string and replace with ''.

names(df) <- sub('_\\d+$', '', names(df))

或者正如@David Arenburg 提到的,它可以是 _ 之后的任何字符(.*)中的一个或多个(将匹配诸如 var1_1 之类的模式)var1_d3533 等)

Or as @David Arenburg mentioned, it can be one or more of any character (.*) after the _ (which will match patterns such var1_1, var1_d3533 etc.)

names(df) sub("_.*", "", df)

或者我们使用paste(@jogo 的评论)

Or we use paste (@jogo's comment)

names(df) <- c("Ind", paste0("var", 1:100))

这篇关于删除列名中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆