1
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.

2

2 Answers 2

4

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" 
Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

R allows using regular quotes here but the documentation recommends against doing so (it’s incredibly confusing because the resulting token isn’t treated as a character string by the R interpreter; R only supports it for reasons of backwards compatibility).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.