具有选择功能的列的重命名序列 [英] dplyr- renaming sequence of columns with select function

查看:169
本文介绍了具有选择功能的列的重命名序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 dplyr 中重命名我的列。我发现用选择函数。但是,当我尝试按顺序重命名一些选定的列时,我无法重命名我想要的格式。

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)

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

即使我从 CC0,CC1,CC2,CC3 CC >输出给出自动从 CC1 开头。
我如何解决这个问题?

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?

推荐答案

我想你会有一个更容易的时间, select _ function:

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

这篇关于具有选择功能的列的重命名序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆