search and replace functions to rename columns

ぐ巨炮叔叔 提交于 2020-06-27 17:43:09

问题


I have data frame like this

> 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

and, desired output

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


回答1:


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="_"))

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)) 


来源:https://stackoverflow.com/questions/37849594/search-and-replace-functions-to-rename-columns

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