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:
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.