簡體   English   中英

重命名包含空格的列時,dplyr rename_會產生錯誤

[英]dplyr rename_ produces an error when renaming columns with spaces

rename_按預期用於非病理列名稱

%>% rename_(foo = 'testcol')

但是,如果我想重命名一個有空格的列呢?

%>% 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的帖子中的類似語法

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函數lazyeval內部使用lazyeval lazyeval::as.lazy的字符方法無法處理空格。 一個可能的解決方法是around character strings with spaces inside as.lazy.character`中添加around character strings with spaces insidearound character strings with spaces inside

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM