用`-`符号重命名R中的列

时间:2019-04-01 11:02:31

标签: r dplyr data.table rename

temp <- data.frame(re_ply = rnorm(10), total_ID = rnorm(10),  re_ask = rnorm(10))

我要将列更改为: re_plyRe-ply total_IDtotal_id re_askRe-ask

temp <- temp %>% dplyr::rename(Re-ply = re_ply,
                           total_id = total_ID,
                           Re-ask = re_ask)

此操作无效,因为在Re-ply中,并且Re-ask的{​​{1}}符号无效。我该如何解决。我知道在列名中使用-符号并不理想,但只是想检查一下这是否完全可能。我唯一的目标是如上所述重命名该文件,将其写为-并在excel中进行其他处理。

2 个答案:

答案 0 :(得分:4)

可以使用rename完成此操作。您只需将带有特殊字符的列名称放在“`”符号内:

temp <- temp %>% dplyr::rename(`Re-ply` = re_ply,
                                total_id = total_ID,
                                `Re-ask` = re_ask)
names(temp)
[1] "Re-ply"   "total_id" "Re-ask" 

答案 1 :(得分:0)

简单地将所有参数名称用“特殊字符”(如减号)包装在反引号或引号中,例如rename("Re-ply" = re_ply)。而且,您可以使用半引号,如果需要旧名称=新名称,而不是新名称=旧名称,则可以使用sjmisc::var_rename()

library(rlang)
library(dplyr)
library(sjmisc)

temp <- data.frame(
  re_ply = rnorm(10), 
  total_ID = rnorm(10),  
  re_ask = rnorm(10)
)


old_name <- "re_ply"
new_name <- "Re-ply"

temp %>% colnames()
#> [1] "re_ply"   "total_ID" "re_ask"

temp %>% 
  dplyr::rename(
    "Re-Ply" = re_ply,
    total_id = total_ID,
    "Re-ask" = re_ask
  ) %>% 
  colnames()
#> [1] "Re-Ply"   "total_id" "Re-ask"

temp %>% 
  dplyr::rename(
    !! new_name := !! old_name,
    total_id = total_ID,
    "Re-ask" = re_ask
  ) %>% 
  colnames()
#> [1] "Re-ply"   "total_id" "Re-ask"

temp %>% 
  sjmisc::var_rename(
    re_ply = "Re-ply",
    total_ID = total_id,
    re_ask = "Re-ask"
  ) %>% 
  colnames()
#> [1] "Re-ply"   "total_id" "Re-ask"

temp %>% 
  sjmisc::var_rename(
    !! old_name := !! new_name,
    total_ID = "total_id",
    re_ask = "Re-ask"
  ) %>% 
  colnames()
#> [1] "Re-ply"   "total_id" "Re-ask"

reprex package(v0.2.1)于2019-04-01创建