如何处理列名中的空格?

Rob*_*ong 27 r ggplot2

我知道如果变量名称中没有空格,则首选.我的情况是需要出版品质的图表,所以轴和图例需要有正确格式的标签,即带空格.因此,例如,在开发过程中,我可能会有名为"Pct.On.OAC"和Age.Group的变量,但在我的最终情节中,我需要出现"%on OAC"和"Age Group":

'data.frame':   22 obs. of  3 variables:
 $ % on OAC           : Factor w/ 11 levels "0","0.1-9.9",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ Age Group          : Factor w/ 2 levels "Aged 80 and over",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Number of Practices: int  47 5 33 98 287 543 516 222 67 14 ...
Run Code Online (Sandbox Code Playgroud)

但是当我试图绘制这些时:

ggplot(dt.m, aes(x=`% on OAC`,y=`Number of Practices`, fill=`Age Group`)) +
    geom_bar()
)
Run Code Online (Sandbox Code Playgroud)

没问题.但是当我添加一个方面时:

ggplot(dt.m, aes(x=`% on OAC`,y=`Number of Practices`, fill=`Age Group`)) +
    geom_bar() +
    facet_grid(`Age Group`~ .) 
Run Code Online (Sandbox Code Playgroud)

我得到Error in[.data.frame(base, names(rows)) : undefined columns selected

如果我Age Group改为Age.Group那么它工作正常,但正如我所说,我不希望点出现在标题图例中.

所以我的问题是:

  1. 有关于facet问题的解决方法吗?
  2. 当我想要最终的情节包含它们时,是否有更好的通用方法来处理变量名中的空格(和其他字符)问题?我想我可以手动覆盖它们,但这看起来好像很多.

Dir*_*tel 24

你问"有没有更好的通用方法来处理变量名中的空格(和其他字符)的问题",是的,有一些:

  • 只是不要使用它们,因为你在这里遇到的事情会破坏
  • 使用该make.names()函数创建安全名称; R也使用它来创建标识符(例如,通过使用下划线表示空格等)
  • 如果必须,请使用反引号保护不安全的标识符.

最后两点的示例:

R> myvec <- list("foo"=3.14, "some bar"=2.22)
R> myvec$'some bar' * 2
[1] 4.44
R> make.names(names(myvec))
[1] "foo"      "some.bar"
R> 
Run Code Online (Sandbox Code Playgroud)


Jor*_*eys 17

这是包ggplot2中的一个"错误",它来自as.data.frame()内部ggplot2函数中的函数quoted_df将名称转换为语法上有效的名称.这些语法上有效的名称在原始数据帧中找不到,因此出错.

提醒你 :

语法上有效的名称由字母,数字和点或下划线字符组成,并以字母或点开头(但点后面不能有数字)

这是有原因的.还有一个原因可以解释为什么ggplot允许您使用labs例如使用以下有效名称的虚拟数据集来设置标签:

X <-data.frame(
  PonOAC = rep(c('a','b','c','d'),2),
  AgeGroup = rep(c("over 80",'under 80'),each=4),
  NumberofPractices = rpois(8,70)
  ) 
Run Code Online (Sandbox Code Playgroud)

您可以使用最后的实验来使此代码正常工作

ggplot(X, aes(x=PonOAC,y=NumberofPractices, fill=AgeGroup)) +
  geom_bar() +
  facet_grid(AgeGroup~ .) + 
  labs(x="% on OAC", y="Number of Practices",fill = "Age Group")
Run Code Online (Sandbox Code Playgroud)

生产

在此输入图像描述

  • PS:正如@DirkEddelbuettel 所指出的,afaik 函数`as.data.frame` 在内部使用函数`make.names()` 来“纠正”这些名称(即创建有效的标识符)。 (2认同)