Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - How to add a suffix onto column names based on existing column name?

At the moment, the code below is not very reproducible as I am adding the suffix based on column numbers. How would I modify this code to add the suffix to all columns beginning with "rs" instead of using column numbers?

# make data 

df <- data.frame(y1 = rbinom(100, 1, 0.5), y2 = rbinom(100, 1, 0.3), y3 = rbinom(100, 1, 0.2), y4 = rbinom(100, 1, 0.22),
                       rs1 = rnorm(100), rs2 = rnorm(100), rs3 = rnorm(100),
                       rs4 = rnorm(100), rs5 = rnorm(100), rs6 = rnorm(100))


# add suffix to column names beginning with rs
colnames(df)[5:10] <- paste(colnames(df)[5:10], "C", sep = "_")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use grep or startsWith from base R

nm1 <- startsWith(names(df), "rs")
# // or with grep
nm1 <- grep("^rs", names(df))
names(df)[nm1] <- paste0(names(df)[nm1], "_C")

Or using rename_at from dplyr

library(dplyr)
library(stringr)
df <- df %>%
  rename_at(vars(starts_with('rs')), ~ str_c(., '_C'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...