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

Categories

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 = "_")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...