2

I would like to replace columns that contain "score" string with predefined names.

Here is a simple example dataset and my desired column names to replace.

df1 <- data.frame(a = c(1,2,3,4,5),
                  b = c(5,6,7,8,9),
                  c.1_score = c(10,10,2,3,4),
                  a.2_score= c(1,3,5,6,7))

replace.cols <- c("c_score", "a_score")

The number of columns changes each trial. So whenever the column name includes _score, I would like to replace them with my predefined replace.cols names.

The desired col names should be a b c_score and a_score.

Any thought? Thanks.

1 Answer 1

2

We can use rename_at

library(dplyr)
df1 <- df1 %>%
          rename_at(vars(ends_with('score')), ~ replace.cols)

df1
#  a b c_score a_score
#1 1 5      10       1
#2 2 6      10       3
#3 3 7       2       5
#4 4 8       3       6
#5 5 9       4       7

or with str_remove

library(stringr)
df1 %>%
     rename_at(vars(ends_with('score')), ~ str_remove(., '\\.\\d+'))

Or using base R (assuming the column names order is maintained in 'replace.cols')

names(df1)[endsWith(names(df1), 'score')] <- replace.cols
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.