Reputation: 619
The names of the columns in my data frame all have the same format. All the column names/vector names start "jjk_" and then read the correct name of the column. Here is how it looks:
jjk_LEFT. jjk_COLD. jjk_TOP
4 7 55
6 12 3
7 23 6
...
All I want to do is remove the "jjk_" so that the column names just read all that follows after the underscore. Thus, I would like the final data frame to look like this:
LEFT. COLD. TOP
4 7 55
6 12 3
7 23 6
...
Upvotes: 0
Views: 107
Reputation: 3269
colnames(df) = gsub("jjk_", "", colnames(df))
# LEFT. COLD. TOP
# 1 4 7 55
# 2 6 12 3
# 3 7 23 6
structure(list(jjk_LEFT. = c(4L, 6L, 7L),
jjk_COLD. = c(7L, 12L, 23L),
jjk_TOP = c(55L, 3L, 6L)),
class = "data.frame", row.names = c(NA,-3L)) -> df
Upvotes: 1
Reputation: 887951
An option with trimws
from base R
names(df) <- trimws(names(df), whitespace = '^\\w+_')
names(df)
#[1] "LEFT." "COLD." "TOP"
df <- structure(list(jjk_LEFT. = c(4L, 6L, 7L), jjk_COLD. = c(7L, 12L,
23L), jjk_TOP = c(55L, 3L, 6L)), class = "data.frame", row.names = c(NA,
-3L))
Upvotes: 0
Reputation: 102880
You can try setNames
with gsub
setNames(df,gsub("^\\w+_","",names(df)))
which gives
LEFT. COLD. TOP
1 4 7 55
2 6 12 3
3 7 23 6
Data
> dput(df)
structure(list(jjk_LEFT. = c(4L, 6L, 7L), jjk_COLD. = c(7L, 12L,
23L), jjk_TOP = c(55L, 3L, 6L)), class = "data.frame", row.names = c(NA,
-3L))
Upvotes: 0