开发者

Calling qplot with data.frames with string col names

I have a data.frame created with:

d <- data.frame("name 1"=1, "name 2"=2)

Calling qplot("name 1", "name 2", data=d) does not work, for obvious reasons. Is it possible to make it work using 开发者_JAVA技巧some mechanism? I've tried as.name but that also doesn't work.


There are two issues at work here:

  1. How to use non-standard yet syntactically valid component names, and
  2. What R is doing when creating the names component for a data frame.

I'll take these in reverse order.

When you create a data frame using data.frame(), the default is the check the names of the components for validity. From ?data.frame we have:

check.names: logical.  If ‘TRUE’ then the names of the variables in the
          data frame are checked to ensure that they are syntactically
          valid variable names and are not duplicated.  If necessary
          they are adjusted (by ‘make.names’) so that they are.

What this means is that for the the OPs d, created using

d <- data.frame("name 1" = 1, "name 2" = 2)

will have these names:

> names(d)
[1] "name.1" "name.2"

This behaviour can be suppressed via

> names(data.frame("name 1" = 1, "name 2" = 2, check.names = FALSE))
[1] "name 1" "name 2"

The default behaviour means that we can do things like

> d$name.1
[1] 1

or

> qplot(name.1, name.2, data=d)

but what if you want to have the names as you entered them, with the space? Clearly they don't work as before:

> d <- data.frame("name 1" = 1, "name 2" = 2, check.names = FALSE)
> d
  name 1 name 2
1      1      2
> d$name 1
Error: unexpected numeric constant in "d$name 1"

Non-standard, syntactically valid names need to be quoted when used, using backticks `foo`, or normal quotes "foo", 'foo', e.g.

> d$`name 1`
[1] 1
> d$"name 1"
[1] 1
> d$'name 1'

In the qplot() example, however, the quoted component names doesn't work as expected. The plot is drawn at the character values "name 1" and "name 2" and not the values of those variables, 1 and 2.


You can use backticks to turn strings into symbols:

qplot(`name 1`, `name 2`, data=d)

Glad to hear this worked ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜