0

I am trying to delete the first 4 characters of my column names using stringr. I know how to specify the characters that I want to keep, but since each column length is different, I need to specify the ones that I don't want to keep and I don't know how to do it.

How can I do this?

AndrewGB
  • 16,126
  • 5
  • 18
  • 49
Ajrhjnd
  • 330
  • 1
  • 9

3 Answers3

5

stringr is fine, but here a very good solution exists in base R.

x <- head(state.name)
x 
# [1] "Alabama"    "Alaska"     "Arizona"    "Arkansas"   "California" "Colorado"
substring(x, 5)
# [1] "ama"    "ka"     "ona"    "nsas"   "fornia" "rado"
s_baldur
  • 29,441
  • 4
  • 36
  • 69
  • this gives me something like a list, it does not substitute the names of the columns – Ajrhjnd Dec 22 '21 at 18:56
  • The input should be a vector. So if you want to modify the (column)names of a `data.frame` you could `names(df) <- substring(names(df), 5)` – s_baldur Dec 22 '21 at 18:57
  • Now I have arrived to the solution. Thanks – Ajrhjnd Dec 22 '21 at 19:03
  • 1
    I agree that there should be no need to go to the `stringr` package for this, but if it is strictly required (for some reason), then replace `substring` with `stringr::str_sub` and it all works the same. (Though `substring` is over 3x *faster* with this sample data. It doesn't approach speed-parity until `length(x)` here is in the mid-1000s.) – r2evans Dec 22 '21 at 19:14
3

You may find this useful to rename columns.

library(dplyr)
library(stringr)

df %>% 
  rename_with(str_sub, start = 5L)

If you don't want to do it for all of the columns, you can use the .cols argument.

# like this
iris %>% 
  rename_with(str_sub, start = 5L, .cols = starts_with("Sepal"))

# or this
iris %>% 
  rename_with(str_sub, start = 5L, .cols = 1:2)

# or this, and so on...
iris %>% 
  rename_with(str_sub, start = 5L, .cols = c("Petal.Length", "Species"))
0

This is not the best way but should be here for offering an alternative with Base R.

substr(state.name,5,nchar(state.name))
# [1] "ama"        "ka"         "ona"        "nsas"       "fornia"     "rado"       "ecticut" 
maydin
  • 3,715
  • 3
  • 10
  • 27