89_Simple
89_Simple

Reputation: 3805

renaming columns in R with `-` symbol

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

I want to change the column as: re_ply to Re-ply total_ID to total_id re_ask to Re-ask

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

This won't work since in Re-ply and Re-ask has the - symbol won't work. How can I fix it. I know it is not ideal to have a - symbol in the column name but just wanted to check if this is possible at all. My only goal is to rename this file as shown above, write it out as .csv and do other processing in excel.

Upvotes: 1

Views: 2423

Answers (2)

Daniel
Daniel

Reputation: 7832

Simply put, wrap all argument-names with "special chars" (like minus) in backticks or quotes, e.g. rename("Re-ply" = re_ply). And you can use quasiquotation, or sjmisc::var_rename() if you want old name = new name instead new name = old name.

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"

Created on 2019-04-01 by the reprex package (v0.2.1)

Upvotes: 0

symbolrush
symbolrush

Reputation: 7457

This can be done using rename. You just have to put the column names with special charcters inside the "`" sign:

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" 

Upvotes: 4

Related Questions