Extract substrings of character vector for column names

Hello,

I want to rename specific columns in my dataset (columns 15 to 29) by extracting the first 2 or 3 characters in the string. Here is my code:

colnames(d[15:29]) <- sapply(colnames(d[15:29]), function(x){
  substr(x, 1,3)
})

.... And nothing happens. What am I doing wrong?

Here is the first row of my data so you can get the column names:

structure(list(STIS. = "1000", Month = "July", Ship = "LE2", 
    Lake = "Michigan", Site = "EAS5", Station = NA_character_, 
    Research.Project = "CSMI2021", Date = "7/17/2021", Time..EST. = "15:01 (CDT)", 
    Site.Depth..m. = 49, Integrated.depths..m. = NA, Separate.depths..m. = 5, 
    DCL. = "N", Stratified..Unstratified. = "Stratified", NH4.ug.N.L = 19.7, 
    NOx.ug.N.L = 347, SRP.ug.P.L = 3.51, TN.ug.N.L = 509, TP.ug.P.L = 9.6, 
    K..mg.L = 1.36, Na..mg.L = 7.26, Ca...mg.L = 31.18, Mg...mg.L = 12.21, 
    Cl..mg.L = 13, SO4..mg.L = 22.83, Si.mg.SiO2.L = 4.71, chl.a....ug.L = 0.63, 
    TSS.mg.L = 0.507, VSS.mg.L = 0.513), row.names = 1L, class = "data.frame")

Thanks so much!

I believe the modification below gives the intended result.

colnames(d)[15:29] <- sapply(colnames(d)[15:29], function(x){
  substr(x, 1,3)
})

colnames(d)[15:29]
#>  [1] "NH4" "NOx" "SRP" "TN." "TP." "K.." "Na." "Ca." "Mg." "Cl." "SO4" "Si."
#> [13] "chl" "TSS" "VSS"

Created on 2022-12-06 with reprex v2.0.2.9000

1 Like

Thank you so much!

I then I want to remove the period from any of the column names that have periods. I tried this:

colnames(d)[15:29] <- sapply(colnames(d)[15:29], function(x){
  gsub(".", "", x)
})

But then all my column names were erased - the names were just empty. Any idea what I did this time? Haha.

You're welcome! You need to add a double slash in front of your period.

colnames(d)[15:29] <- sapply(colnames(d)[15:29], function(x){
  gsub('\\.', '', substr(x, 1,3))
})
1 Like

Wow, thank you so much!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.