I want to add a string of text at the end of the column names in my data frame. How do I do this?
Example data (where I want to change column names A
, B
, C
, D
, E
to Atext
, Btext
, Ctext
, Dtext
, Etext
):
df <- structure(list(User_ID = 1:4, A = c(0.815353067, 0.698314902, 0.774619233, 0.949620322),
B = c(0.684046246, 0.427028078, 0.579449798, 0.977426626),
C = c(0.101562005, 0.943064479, 0.19946195, 0.70068721),
D = c(0.525384365, 0.638082727, 0.651924335, 0.112375646),
E = c(0.415664129, 0.006406548, 0.85036104, 0.510504667)),
class = "data.frame", row.names = c(NA, -4L))
CodePudding user response:
Use grep
to find the letter name columns, along with paste
to concatenate the string text
to the end:
names.change <- grep("^[A-Z] $", names(df))
names(df)[names.change] <- paste0(names(df)[names.change], "text")
df
User_ID Atext Btext Ctext Dtext Etext
1 1 0.8153531 0.6840462 0.1015620 0.5253844 0.415664129
2 2 0.6983149 0.4270281 0.9430645 0.6380827 0.006406548
3 3 0.7746192 0.5794498 0.1994619 0.6519243 0.850361040
4 4 0.9496203 0.9774266 0.7006872 0.1123756 0.510504667
CodePudding user response:
I'd prefer it in a one-liner with dplyr::rename_with
:
library(dplyr)
df %>% rename_with(~paste0(., "Text"), grep("^[A-Z]$", names(.)))
Output:
User_ID AText BText CText DText EText
1 1 0.8153531 0.6840462 0.1015620 0.5253844 0.415664129
2 2 0.6983149 0.4270281 0.9430645 0.6380827 0.006406548
3 3 0.7746192 0.5794498 0.1994619 0.6519243 0.850361040
4 4 0.9496203 0.9774266 0.7006872 0.1123756 0.510504667
CodePudding user response:
Here is a base R solution without grepl
:
colnames(df)[-1] <- paste0(colnames(df)[-1], "text")
output:
User_ID Atext Btext Ctext Dtext Etext
1 1 0.8153531 0.6840462 0.1015620 0.5253844 0.415664129
2 2 0.6983149 0.4270281 0.9430645 0.6380827 0.006406548
3 3 0.7746192 0.5794498 0.1994619 0.6519243 0.850361040
4 4 0.9496203 0.9774266 0.7006872 0.1123756 0.510504667
CodePudding user response:
I would also use rename_with
. But i think we can use the .cols
argument, so we can include a selection helper before the call to rename_with
, obviating the need for grep
.
df %>% rename_with(.cols=matches('[A-E]'), ~paste0(.x, 'text'))
If the selected columns are consistently A-Z, the selection can be even simpler:
df %>% rename_with(~paste0(.x, 'text'), A:E)
output
User_ID Atext Btext Ctext Dtext Etext
1 1 0.8153531 0.6840462 0.1015620 0.5253844 0.415664129
2 2 0.6983149 0.4270281 0.9430645 0.6380827 0.006406548
3 3 0.7746192 0.5794498 0.1994619 0.6519243 0.850361040
4 4 0.9496203 0.9774266 0.7006872 0.1123756 0.510504667