user10072474
user10072474

Reputation:

Renaming multiple columns in R

I hope this is not a duplicate question as I could not find an answer I was interested in using. I have 70 columns and I want to rename them. I know several approaches as an example:

df1<-setmames (df1, c("BA1", "MA2", "NA3"...), c( "AB1","QB2","Q3"...))

But these approaches are not helpful as we have a very large scripts. I wonder if we could do it with a small script using tidyverse?

Just as an example I can show three columns, assuming I have this table:

AB1	AB2	AB3
12	13	13
12	13	13
12	11	13
12	13	17
12	13	16

I want to get this table

MZ1	MZ2	MZ3
12	13	13
12	13	13
12	11	13
12	13	17
12	13	16

Considering this is just an example , I have 70 columns.

Upvotes: 2

Views: 5074

Answers (1)

akrun
akrun

Reputation: 887951

We can use the index or column names

names(df1)[1:70] <- v1

where

 v1<- c("AB1", "QB2", ...)

With dplyr, we can use rename_at

library(dplyr)
library(stringr)
df1 <- df1 %>%
          rename_at(1:70, ~ v1)

If we are renaming columns that starts with `AB'

names(df1)
#[1] "x1"  "x2"  "AB1" "AB2"

df1 %>%
   rename_at(vars(matches('^AB\\d+$')), ~ str_replace(., 'AB', 'MZ'))
#  x1 x2        MZ1       MZ2
#1  1  6 -0.5458808 0.6048889
#2  2  7  0.5365853 0.3707349
#3  3  8  0.4196231 0.6716903
#4  4  9 -0.5836272 0.6729823
#5  5 10  0.8474600 0.3204306

Or in base R

i1 <- grep("^AB\\d+$", names(df1))
names(df1)[i1] <- sub("AB", "MZ", names(df1)[i1])

Update

df2 <- df2 %>%
         rename_at(vars(matches("^AB\\d+$")), ~ str_replace(., "AB", "MZ"))
df2
#  MZ1 MZ2 MZ3
#1  12  13  13
#2  12  13  13
#3  12  11  13
#4  12  13  17
#5  12  13  16

data

set.seed(24)
df1 <- data.frame(x1 = 1:5, x2 = 6:10, AB1 = rnorm(5), AB2 = runif(5))

original data values

df1
#  x1 x2        AB1       AB2
#1  1  6 -0.5458808 0.6048889
#2  2  7  0.5365853 0.3707349
#3  3  8  0.4196231 0.6716903
#4  4  9 -0.5836272 0.6729823
#5  5 10  0.8474600 0.3204306

Updated data from OP's post

df2 <- structure(list(AB1 = c(12L, 12L, 12L, 12L, 12L), AB2 = c(13L, 
 13L, 11L, 13L, 13L), AB3 = c(13L, 13L, 13L, 17L, 16L)),
  class = "data.frame", row.names = c(NA, -5L))

Upvotes: 7

Related Questions