renaming certain column names with paste0()

I have a lot of variables and the column numbers will change and I'm trying to subset by different columns for some of my plots. I need to keep all of my data together but need a way to globally identify columns. After I get the suffixes pasted to the variable names, I plan to use grepl to grab all of the columns that I need for plots.

The following code gives me the "_Z" for all of the columns. How would I do it with just indicator2 and indicator5? Again, I can't use column numbers. I'm going to have to use the many (~100) column names to rename them.

df_1 <- data.frame(
categorical = c("A","B","C","A","B","A","C","C","C","A","A","C","C","C","A","C","A","B","A","C"),
indicator1 = c(1,0,1,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,1),
indicator2 = c(1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0),
indicator3 = c(1,0,1,0,1,0,1,0,1,0,0,1,1,0,1,0,1,0,1,0),
indicator4 = c(0,1,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0),
indicator5 = c(0,0,1,1,1,0,1,0,1,0,1,1,1,1,1,0,0,0,0,0),
continuous1 = c(2.3,3.4,6.6,5.5,6,7,11,12.3,13,5,2.4,3.6,6.3,5.2,5,6.6,11.3,12,14,5),
gender = c("M","M","F","F","F","F","F","F","M","U","U","F","M","M","F","F","F","U","M","F"))

print(df_1)
#summary(df_1)

temp <- names(df_1)

put a "_Z" at end

names <- paste0(temp, "_Z")

names(df_1) <- names
df_1

If you just want to rename two columns, you could do something like the following.

df_1 <- data.frame(
  categorical = c("A","B","C","A","B","A","C","C","C","A","A","C","C","C","A","C","A","B","A","C"),
  indicator1 = c(1,0,1,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,1),
  indicator2 = c(1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0),
  indicator3 = c(1,0,1,0,1,0,1,0,1,0,0,1,1,0,1,0,1,0,1,0),
  indicator4 = c(0,1,0,0,1,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0),
  indicator5 = c(0,0,1,1,1,0,1,0,1,0,1,1,1,1,1,0,0,0,0,0),
  continuous1 = c(2.3,3.4,6.6,5.5,6,7,11,12.3,13,5,2.4,3.6,6.3,5.2,5,6.6,11.3,12,14,5),
  gender = c("M","M","F","F","F","F","F","F","M","U","U","F","M","M","F","F","F","U","M","F"))
names(df_1)
#> [1] "categorical" "indicator1"  "indicator2"  "indicator3"  "indicator4" 
#> [6] "indicator5"  "continuous1" "gender"
NMS <- names(df_1)
names(df_1) <- ifelse(NMS %in% c("indicator2", "indicator5"), paste0(NMS, "_Z"), NMS)
names(df_1)
#> [1] "categorical"  "indicator1"   "indicator2_Z" "indicator3"   "indicator4"  
#> [6] "indicator5_Z" "continuous1"  "gender"

Created on 2020-02-17 by the reprex package (v0.3.0)

1 Like

Yep, that worked. I had 100 columns but I was going to have to do it by column name anyways. Thanks! You are a big help!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.