Alexander
Alexander

Reputation: 4635

dplyr- renaming sequence of columns with select function

I'm trying to rename my columns in dplyr. I found that doing it with select function. however when I try to rename some selected columns with sequence I cannot rename them the format that I want.

test = data.frame(x = rep(1:3, each = 2),
              group =rep(c("Group 1","Group 2"),3),
              y1=c(22,8,11,4,7,5),
              y2=c(22,18,21,14,17,15),  
              y3=c(23,18,51,44,27,35),
              y4=c(21,28,311,24,227,225))

CC <- paste("CC",seq(0,3,1),sep="")
aa<-test%>%
select(AC=x,AR=group,CC=y1:y4)

head(aa)

  AC      AR CC1 CC2 CC3 CC4
1  1 Group 1  22  22  23  21
2  1 Group 2   8  18  18  28
3  2 Group 1  11  21  51 311
4  2 Group 2   4  14  44  24
5  3 Group 1   7  17  27 227
6  3 Group 2   5  15  35 225

the problem is even I set CC value from CC0, CC1, CC2, CC3 the output gives automatically head names starting from CC1. how can I solve this issue?

Upvotes: 1

Views: 5921

Answers (1)

hrbrmstr
hrbrmstr

Reputation: 78792

I think you'll have an easier time crating such an expression with the select_ function:

library(dplyr)

test <- data.frame(x=rep(1:3, each=2),
                   group=rep(c("Group 1", "Group 2"), 3),
                   y1=c(22, 8, 11, 4, 7, 5),
                   y2=c(22, 18, 21, 14, 17, 15),
                   y3=c(23, 18, 51, 44, 27, 35),
                   y4=c(21, 28, 311,24, 227, 225))

# build out our select "translation" named vector
DQ <- paste0("y", 1:4)
names(DQ) <- paste0("DQ", seq(0, 3, 1))

# take a look
DQ

##  DQ0  DQ1  DQ2  DQ3 
## "y1" "y2" "y3" "y4"

test %>%
  select_("AC"="x", "AR"="group", .dots=DQ)

##   AC      AR DQ0 DQ1 DQ2 DQ3
## 1  1 Group 1  22  22  23  21
## 2  1 Group 2   8  18  18  28
## 3  2 Group 1  11  21  51 311
## 4  2 Group 2   4  14  44  24
## 5  3 Group 1   7  17  27 227
## 6  3 Group 2   5  15  35 225

Upvotes: 8

Related Questions