dplyr rename_ 在用空格重命名列时产生错误

dplyr rename_ produces an error when renaming columns with spaces

rename_ 对非病态列名称按预期工作

%>% rename_(foo = 'testcol')

但是,如果我想重命名具有 space 的列怎么办?

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

我收到一条错误消息:

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

我可以使用 make.names,但是如果没有这个额外的步骤就无法重命名列吗?

你可以试试backquotes

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

使用可重现的例子

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

或使用 rename_(尽管我不确定这是否是正确的语法,因为通常需要 .dots。)使用来自 OP 的 post

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

数据

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

这是此行为的根本原因。要解决这个问题,@akrun 的答案可能更合适。

大多数 dplyr 函数在内部使用 lazyevallazyeval::as.lazy 的字符方法不能处理空格。一个可能的解决方法是添加 around character strings with spaces insideas.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)
}

或者更好(来自@hadley 的建议)

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)
}

这修复了 rename_,以及在内部使用 as.lazy 的任何其他函数:

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