[R] Error creating named character vectors from column names in data frame.
Duncan Murdoch
murdoch.duncan at gmail.com
Fri Oct 7 20:56:53 CEST 2016
On 07/10/2016 1:44 PM, Jorge Cimentada wrote:
> Hi Bert,
>
> Yes, I'm aware of the difference between a and "a" but in terms of object
> classes I don't see the difference between "a" and names(mtcars)[1].
> They're both strings. However, for creating a named character vector, this
> works:
>
> c("a" = "b)
>
> But this doesn't
>
> c(names(mtcars)[1] = "b")
>
> For example:
>
> df <- data.frame("a" = 1:5)
> c("a" = "b")
> c(names(df)[1] = "b") # error
>
> But
>
> identical(names(df)[1], "a")
>
> That was my initial question.
It's a parser issue. The parser is looking for a name before the equal
sign; it finds a string literal, and just to be nice, treats it as a
name. But it never evaluates it as an expression; evaluation happens later.
The parser would be simpler (and apparently less confusing) if it just
refused to accept "a" where a name is needed, but at the time this was
written, there was no other way to express a name that was syntactically
a name, e.g. "bad name". Later the `bad name` notation was added, and
it makes more sense to use that.
If you really want the result you expected, you can get it this way:
structure("b", names = names(df)[1])
Duncan Murdoch
More information about the R-help
mailing list