Remove prefix letter from column variables

女生的网名这么多〃 提交于 2021-02-11 07:53:31

问题


I have all column names that start with 'm'. Example: mIncome, mAge. I want to remove the prefix. So far, I have tried the following:

df %>% 
rename_all(~stringr::str_replace_all(.,"m",""))

This removes all the column names that has the letter 'm'. I just need it removed from from the start. Any suggestions?


回答1:


We need to specify the location. The ^ matches the start of the string (or here the column name). So, if we use ^m, it will only match 'm' at the beginning or start of the string and not elsewhere.

library(dplyr)
library(stringr)
df %>% 
      rename_all(~stringr::str_replace(.,"^m",""))
#   ba Mbgeg gmba cfor
#1  1     2    4    6
#2  2     3    5    7
#3  3     4    6    8

Also, if the case should be ignored, wrap with regex and specify ignore_case = TRUE

df %>%
    rename_all(~ stringr::str_replace(., regex("^m", ignore_case = TRUE), ""))
#  ba bgeg gmba cfor
#1  1    2    4    6
#2  2    3    5    7
#3  3    4    6    8

Another option is word boundary (\\bm), but this could match the beginning of words where there are multi word column names

NOTE: str_replace_all is used when we want to replace multiple occurrence of the pattern. Here, we just need to replace the first instance and for that str_replace is enough.

data

df <- data.frame(mba = 1:3, Mbgeg = 2:4, gmba = 4:6, cfor = 6:8)



回答2:


You can use sub in base R to remove "m" from the beginning of the column names.

names(df) <- sub('^m', '', names(df))



回答3:


Another way you can try

library(tidyverse)
df <- data.frame(mma = 1:2, mbapbe = 1:2)
df2 <- df %>% 
  rename_at(vars(c("mma", "mbapbe")) ,function(x) gsub("^m", "", x))
#   ma bapbe
# 1  1     1
# 2  2     2 


来源:https://stackoverflow.com/questions/63459369/remove-prefix-letter-from-column-variables

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