Reputation: 75
I am trying to change column names using colnames() function in R, but I want to keep the first two column names unchanged. For instance,
x <- c("A", "B", "C")
x2 <- c( "D", "E", "F")
ch <- c("G", "H", "I")
ch2 <- c("J", "K", "L")
ch3 <- c("M", "N", "O")
df <- data.frame(x, x2, ch, ch2, ch3)
x x2 ch ch2 ch3
1 A D G J M
2 B E H K N
3 C F I L O
I just want to add "x_" in front of these columns so I would use
colnames(df) <- paste("x", colnames(df), sep = "_")
which will change their names to
x_x x_x2 x_ch x_ch2 x_ch3
1 A D G J M
2 B E H K N
3 C F I L O
with all the column names changed, which is not what I want to do. How can I keep the first two column names unchanged while changing rest of the column names? I've tried various different ways but so far I can only keep the first two column names unchanged and the rest column names erased. If it's possible, I would like to use only dpylr or just basic R. Thank you in advance!
Upvotes: 1
Views: 2959
Reputation: 61204
Another alternative in R base: sub
> names(df) <- sub("(^ch.*)","x_\\1", names(df))
> df
x x2 x_ch x_ch2 x_ch3
1 A D G J M
2 B E H K N
3 C F I L O
Upvotes: 1
Reputation: 47330
In base R:
i <- startsWith(names(df),"ch")
names(df)[i] <- paste0("x_",names(df)[i])
# x x2 x_ch x_ch2 x_ch3
# 1 A D G J M
# 2 B E H K N
# 3 C F I L O
Upvotes: 1
Reputation: 887521
We could use rename_at
from dplyr
library(dplyr)
df %>%
rename_at(vars(matches("ch")), ~ paste0("x_", .))
# x x2 x_ch x_ch2 x_ch3
#1 A D G J M
#2 B E H K N
#3 C F I L O
Upvotes: 4
Reputation: 848
Specify the starting column number to add the string:
x <- c("A", "B", "C")
x2 <- c( "D", "E", "F")
ch <- c("G", "H", "I")
ch2 <- c("J", "K", "L")
ch3 <- c("M", "N", "O")
df <- data.frame(x, x2, ch, ch2, ch3)
colnames(df)[3:ncol(df)] <- paste("x", colnames(df[3:ncol(df)]), sep = "_")
df
Upvotes: 1
Reputation: 737
Rather than apply that function to all colnames
, use []
notation to apply it to a subset of columns
colnames(df)[3:ncol(df)] <- paste("x", colnames(df)[3:ncol(df)], sep = "_")
And welcome to StackOverflow!
Upvotes: 2