dplyr - 重命名由 readr 创建的列 [EMPTY]
dplyr - Rename column [EMPTY] created by readr
当使用 readr_0.1.1
读取缺少字段名称的 .csv 文件时,名称会自动设置为 [EMPTY]
:
library("readr")
library("dplyr")
df <- read_csv(",foo\n1,bar")
> names(df)
[1] "[EMPTY]" "foo"
我正在尝试使用 dplyr_0.4.2
重命名 "[EMPTY]"
,但找不到正确的解决方案。
我试过:
> rename(df, baz = [EMPTY])
Error: unexpected '[' in "rename(df, baz = ["
> rename_(df, "baz" = "[EMPTY]")
Error in parse(text = x) : <text>:1:1: unexpected '['
1: [
^
正确的做法是什么?
您可以使用
dplyr::rename(df, baz = `[EMPTY]`)
我们使用反引号,而不是引号,因为我们指的是 "non-standard variable name" 例如:
df$`[EMPTY]`
来自?Quotes
Identifiers consist of a sequence of letters, digits, the period (.)
and the underscore. They must not start with a digit nor underscore,
nor with a period followed by a digit. Reserved words are not valid
identifiers.
The definition of a letter depends on the current locale, but only
ASCII digits are considered to be digits.
Such identifiers are also known as syntactic names and may be used
directly in R code. Almost always, other names can be used provided
they are quoted. The preferred quote is the backtick (`), and deparse
will normally use it, but under many circumstances single or double
quotes can be used (as a character constant will often be converted to
a name).
当使用 readr_0.1.1
读取缺少字段名称的 .csv 文件时,名称会自动设置为 [EMPTY]
:
library("readr")
library("dplyr")
df <- read_csv(",foo\n1,bar")
> names(df)
[1] "[EMPTY]" "foo"
我正在尝试使用 dplyr_0.4.2
重命名 "[EMPTY]"
,但找不到正确的解决方案。
我试过:
> rename(df, baz = [EMPTY])
Error: unexpected '[' in "rename(df, baz = ["
> rename_(df, "baz" = "[EMPTY]")
Error in parse(text = x) : <text>:1:1: unexpected '['
1: [
^
正确的做法是什么?
您可以使用
dplyr::rename(df, baz = `[EMPTY]`)
我们使用反引号,而不是引号,因为我们指的是 "non-standard variable name" 例如:
df$`[EMPTY]`
来自?Quotes
Identifiers consist of a sequence of letters, digits, the period (.) and the underscore. They must not start with a digit nor underscore, nor with a period followed by a digit. Reserved words are not valid identifiers.
The definition of a letter depends on the current locale, but only ASCII digits are considered to be digits.
Such identifiers are also known as syntactic names and may be used directly in R code. Almost always, other names can be used provided they are quoted. The preferred quote is the backtick (`), and deparse will normally use it, but under many circumstances single or double quotes can be used (as a character constant will often be converted to a name).