Dplyr rename column sequence with select function

I am trying to rename my columns to dplyr . I found that this is done using the select function. however, when I try to rename some selected columns with a sequence, I cannot rename them to the format 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 that even I set the CC value from CC0, CC1, CC2, CC3 , the goals are automatically assigned to the output, starting with CC1 . how can i solve this problem?

+1
source share
1 answer

I think it will be easier for you to erase such an expression using 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 
+6
source

Source: https://habr.com/ru/post/986241/


All Articles