Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to a variable name with spaces?

Tags:

plot

r

ggplot2

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?

like image 447
bshor Avatar asked Dec 29 '10 04:12

bshor


People also ask

Can you have spaces in variable names?

Variable names cannot contain spaces.

How do you declare a variable in space?

You define a variable name that contains spaces or special characters by writing the name between single quotes (') followed by the character n, for example ' My new Variable'n . Make sure that you use the global SAS-option validvarname=any , before you run your code.

How do you write variable names with spaces in Python?

You cannot use spaces in identifiers in Python. Spaces aren't legal in variable names. Use an underscore _ if you must.

What are the 3 rules for naming a variable?

A variable name must start with a letter or an underscore character (_) A variable name cannot start with a digit. A variable name can only contain alpha-numeric characters and underscores ( a-z, A-Z , 0-9 , and _ ) Variable names are case-sensitive (age, Age and AGE are three different variables)


1 Answers

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.

like image 105
Joris Meys Avatar answered Sep 24 '22 06:09

Joris Meys