如何用空格引用变量名? [英] How to refer to a variable name with spaces?

查看:198
本文介绍了如何用空格引用变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ggplot2 中,我如何使用空格来引用一个变量名?

为什么 cp>() ggplot() break用于带引号的变量名称?

例如,这是有效的:

  qplot(x,y,data = a)

code>

但这并不是:

  qplot(x,y,data = a)

数据矩阵中带有空格。例如国家收入。 ggplot2需要数据帧;好的,我可以转换。所以我想尝试一下:

  qplot(国家收入,国家意识形态,data = as。 data.frame(a.matrix))

失败。



在基本的R图形中,我会这样做:

  plot(a.matrix [,State收入],a.matrix [,州意识形态])

p>

有什么想法?

解决方案

回答:因为'x'和'y '被认为是长度一个字符的矢量,而不是一个变量名称。在这里,你会发现为什么在R中使用带空格的变量名或者其他任何编程语言是不明智的。



要用空格引用变量名,可以使用hadleys解决方案

  a.matrix<  -  matrix(rep(1:10,3),ncol = 3) 
colnames(a.matrix)< - c(a name,another name,a third name)

qplot(`a name`,`another name` ,data = as.data.frame(a.matrix))#反引号!

或更正式的

  qplot(get('a name'),get('another name'),data = as.data.frame(a.matrix))

后者可以用于在循环结构中将变量的名称作为字符串传递的构造中:


$ b(pre pre code $ for c(other name,third name)){
print(qplot(get(i),get(一个名字),
data = as.data.frame(a.matrix),xlab = i,ylab =a name))
Sys.sleep(5)
}

不过,最好的解决方案不是使用带空格的变量名。


In ggplot2, how do I refer to a variable name with spaces?

Why do qplot() and ggplot() break when used on variable names with quotes?

For example, this works:

qplot(x,y,data=a)

But this does not:

qplot("x","y",data=a)

I ask because I often have data matrices with spaces in the name. Eg, "State Income". ggplot2 needs data frames; ok, I can convert. So I'd want to try something like:

qplot("State Income","State Ideology",data=as.data.frame(a.matrix))

That fails.

Whereas in base R graphics, I'd do:

plot(a.matrix[,"State Income"],a.matrix[,"State Ideology"])

Which would work.

Any ideas?

解决方案

Answer: because 'x' and 'y' are considered a length-one character vector, not a variable name. Here you discover why it is not smart to use variable names with spaces in R. Or any other programming language for that matter.

To refer to variable names with spaces, you can use either hadleys solution

a.matrix <- matrix(rep(1:10,3),ncol=3)
colnames(a.matrix) <- c("a name","another name","a third name")

qplot(`a name`, `another name`,data=as.data.frame(a.matrix)) # backticks!

or the more formal

qplot(get('a name'), get('another name'),data=as.data.frame(a.matrix))

The latter can be used in constructs where you pass the name of a variable as a string in eg a loop construct :

for (i in c("another name","a third name")){
    print(qplot(get(i),get("a name"),
      data=as.data.frame(a.matrix),xlab=i,ylab="a name"))
    Sys.sleep(5)
}

Still, the best solution is not to use variable names with spaces.

这篇关于如何用空格引用变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆