Dplyr rename_ creates an error when renaming columns with spaces

rename_ works as expected for nonpathological column names

 %>% rename_(foo = 'testcol') 

But what if I wanted to rename a column with a space?

 %>% rename_(foo = 'test col') 

I get an error message:

 Error in parse(text = x) (from #12) : <text>:1:6: unexpected symbol 

I could use make.names , but is there no way to rename a column without this extra step?

+5
source share
2 answers

You can try using backquotes

 %>% rename(foo = `test col`) 

Using a reproducible example

 library(dplyr) df %>% rename(foo = `test col`) %>% head(3) # Col1 foo #1 -0.5458808 C #2 0.5365853 N #3 0.4196231 R 

Or using rename_ (although I'm not sure if this is the correct syntax, as usual .dots ). Using similar syntax from OP message

 df %>% rename_(foo = quote(`test col`)) %>% head(3) # Col1 foo #1 -0.5458808 C #2 0.5365853 N #3 0.4196231 R 

data

  set.seed(24) df <- data.frame(Col1= rnorm(10), 'test col' = sample(LETTERS, 10), check.names=FALSE) 
+9
source

This is the main reason for this behavior. To fix the problem, the answer to @akrun is probably more appropriate.

Most dplyr functions use lazyeval internally. And the character method for lazyeval::as.lazy cannot handle spaces. A possible solution would be to add around character strings with spaces inside as.lazy.character`.

 require(lazyeval) as.lazy.character <- function (x, env = baseenv()){ if (grepl(pattern = "[:space:]", x) & !grepl(pattern = "`", x)) x <- paste0("`", x, "`") lazy_(parse(text = x)[[1]], env) } 

Or even better (from @hadley's suggestion)

 as.lazy.character <- function (x, env = baseenv()){ if (grepl(pattern = "[:space:]", x) & !grepl(pattern = "`", x)) return(as.lazy(as.name(x), env)) lazy_(parse(text = x)[[1]], env) } 

This fixes rename_ as well as any other functions using as.lazy inside:

 dplyr::select_vars_(names(df), "test col") dplyr::rename_(df, foo="test col") dplyr::mutate_(df, "foo" = "test col" ) 
+3
source

All Articles