Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to rename all columns to middle separator in R?

I’m looking for an easy solution to rename my columns to only the middle separator. Here’s some mock data.

dat <- data.frame(
  
  subject = paste("Subject", 1:10),
  CT_tib_all = round(rnorm(10, 0.25, 0.03), 2),
  CT_lum_all = round(rnorm(10, 0.25, 0.03), 2),
  CT_tho_all = round(rnorm(10, 0.25, 0.03), 2)
  
)

I’d like to go from this:

    subject CT_tib_all CT_lum_all CT_tho_all
1 Subject 1       0.25       0.27       0.26
2 Subject 2       0.24       0.19       0.21

To this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    subject        tib        lum        tho
1 Subject 1       0.25       0.27       0.26
2 Subject 2       0.24       0.19       0.21

Thanks!

>Solution :

There may be more elegant solutions, but try this:

colnames(dat)[-1] <- sapply(strsplit(colnames(dat[-1]), "_"), function(x) x[2])

#> dat
#      subject  tib  lum  tho
#1   Subject 1 0.17 0.21 0.20
#2   Subject 2 0.27 0.23 0.28
# ...

This ignores the first (subject) column and sapply() will find everything in between the underscores for the remaining columns.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading