以下代码重命名数据集中的第一列:

require(dplyr)    
mtcars %>%
        setNames(c("RenamedColumn", names(.)[2:length(names(.))]))

Desired results:

                    RenamedColumn cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4                    21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag                21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710                   22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1

Would it be possible to arrive at the same result using rename and column index?

这是:

mtcars %>%
    rename(1 = "ChangedNameAgain")

将失败:

Error in source("~/.active-rstudio-document", echo = TRUE) : 
  ~/.active-rstudio-document:7:14: unexpected '='
6: mtcars %>%
7:     rename(1 =
                ^

类似地,try 使用rename_.[[1]]作为列引用将返回错误.

推荐答案

dplyr0.7.5rlang0.2.1tidyselect0.2.4开始,这就是有效的:

library(dplyr)

rename(mtcars, ChangedNameAgain = 1)

#                     ChangedNameAgain cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4                       21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag                   21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710                      22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive                  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout               18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
# ...

100

rename()的逻辑是new_name = old_name,所以ChangedNameAgain = 11 = ChangedNameAgain更有意义.

我建议:

mtcars %>% rename_(ChangedNameAgain = names(.)[1])
#                     ChangedNameAgain cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4                       21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag                   21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710                      22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive                  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout               18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
# Valiant                         18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1

Edit

自从dplyr的0.6/0.7版本以来,我还没有完全了解基于rlang的新dplyr编程系统.

我最初的答案中使用的rename的下划线后缀版本现在已经被弃用,根据@jzadra的 comments ,它对"foo bar"这样的语法问题名称无论如何都不起作用.

下面是我对新的基于rlang的非标准判断系统的try .请在 comments 中毫不犹豫地告诉我做错了什么:

df <- tibble("foo" = 1:2, "bar baz" = letters[1:2])

# # A tibble: 2 x 2
#     foo `bar baz`
#   <int>     <chr>
# 1     1         a
# 2     2         b

首先,我try 直接使用rename(),但不幸的是,我有一个错误.似乎是FIXME(或者这和FIXME无关?)在源代码中(我使用的是dplyr 0.7.4),因此它可以在future 工作:

df %>% rename(qux = !! quo(names(.)[[2]]))

# Error: Expressions are currently not supported in `rename()`

(Edit: the error message now (dplyr 0.7.5) reads 100)

(Update 2018-06-14: 100 now seems to work, still with dplyr 0.7.5, not sure if an underlying package changed).

这里有一个解决方案,有select个有效.但它并不像rename那样保留列顺序:

df %>% select(qux = !! quo(names(.)[[2]]), everything())

# # A tibble: 2 x 2
#     qux   foo
#   <chr> <int>
# 1     a     1
# 2     b     2

如果我们想把它放在一个函数中,我们必须用:=稍微修改它,以允许在左侧取消引号.如果我们想对字符串和裸变量名这样的输入保持健壮,我们必须使用enquo()quo_name()的"暗魔法"(或者说vignette)(老实说,我不完全理解它的功能):

rename_col_by_position <- function(df, position, new_name) {
  new_name <- enquo(new_name)
  new_name <- quo_name(new_name)
  select(df, !! new_name := !! quo(names(df)[[position]]), everything())
}

这可以将新名称作为字符串使用:

rename_col_by_position(df, 2, "qux")

# # A tibble: 2 x 2
#     qux   foo
#   <chr> <int>
# 1     a     1
# 2     b     2

这将与新名称一起使用,作为一个参考:

rename_col_by_position(df, 2, quo(qux))

# # A tibble: 2 x 2
#     qux   foo
#   <chr> <int>
# 1     a     1
# 2     b     2

这适用于新名称作为裸名称:

rename_col_by_position(df, 2, qux)

# # A tibble: 2 x 2
#     qux   foo
#   <chr> <int>
# 1     a     1
# 2     b     2

即使这样也行:

rename_col_by_position(df, 2, `qux quux`)

# # A tibble: 2 x 2
#   `qux quux`   foo
#        <chr> <int>
# 1          a     1
# 2          b     2

R相关问答推荐

为什么predicate.lm给出的是一个长度与我解析的数据集不同的载体?

基于两个现有列创建新列

geom_Ribbon条件填充创建与数据不匹配的形状(ggplot 2 r)

bslib::card_header中的shine::downloadButton,图标而不是文本

使用across,starts_with和ifelse语句变更多个变量

使用整齐的计算(curl -curl )和杂音

如何得到每四个元素向量R?

矩阵的堆叠条形图,条形图上有数字作为标签

过滤名称以特定字符串开头的文件

使用R中的dist()迭代ID匹配的欧几里德距离

在数据帧列表上绘制GGPUP

R -使用矩阵reshape 列表

R如何将列名转换为更好的年和月格式

手动指定从相同数据创建的叠加图的 colored颜色

以任意顺序提取具有多个可能匹配项的组匹配项

自定义交互作用图的标签

计算来自单独分组的分幅的值的百分位数

当由base::限定时,`[.factor`引发NextMethod错误

整理ggmosaic图的标签

我已经运行了几个月的代码的`Palette()`中出现了新的gglot错误