搜索和替换函数以重命名列 [英] search and replace functions to rename columns

查看:44
本文介绍了搜索和替换函数以重命名列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数据框

> d <- data.frame(team.aaa=1:3, team.aab=4:6, team.aac=7:9)
> d

#   team.aaa team.aab team.aac
#1        1        4        7
#2        2        5        8

,并期望输出

d <- rename(d, c("team.aaa"="aaa_team", "team.aab"="aab_team", "team.aac"="aac_team"))
> d
#  aaa_team aab_team aac_team
#1        1        4        7
#2        2        5        8
#3        3        6        9

我可以使用重命名字符串来完成此操作,但由于数据量巨大,因此希望使用搜索和替换选项
预先感谢

I could do it with rename string, but want to use search and replace option because of huge data volume Many thanks in advance

推荐答案

基于OP帖子中显示的示例,看来之后的后缀部分。应该是前缀,反之亦然。在这种情况下,我们可以使用 sub 捕获不是的字符。后跟,然后捕获其余字符((。*)),并将其替换为相应安排的反向引用。

Based on the example showed in the OP's post, it seems that the suffix part after the . should be the prefix and viceversa. In that case, we can use sub to capture the characters that are not a . followed by ., then capture the rest of the characters ((.*)) and replace it with the backreference arranged accordingly.

names(d) <- sub("([^.]+).(.*)", "\\2_\\1", names(d))
names(d)
#[1] "aaa_team" "aab_team" "aac_team"






或者另一个选择是将字符串除以然后在反转顺序后<粘贴粘贴$


Or another option would be to split the string by . and then paste after reversing the order

sapply(strsplit(names(d), "[.]"), function(x) paste(rev(x), collapse="_"))

或者如评论中提到的@jota一样,如果 team始终是第一个单词,我们可以使用 sub

Or as @jota mentioned in the comments, if 'team' is always the first word, we can make it more compact with sub

sub("team\\.(.*)", "\\1_team", names(d)) 

这篇关于搜索和替换函数以重命名列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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