How to Refer to a Variable Name with Spaces

How to refer to a variable name with spaces?

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.

How to refer to a variable name with spaces in Python?

I suppose you are referring to pandas data frame column, if so, then trimmedWine['residual sugar'] is what you probably need.

How to use spaces in a variable name?

If you want to define a variable with a name that contains a blank character you cannot do it.

You should try removing the quotes with the variable name final_score .

ggplot2 Variable Name with Spaces and tidyeval Syntax

Because it's quoted text, instead of enquo, use rlang::sym

xVariable <- "Month"
yVariable <- "High Temperature"
fun <- function(dat, xvar, yvar) {
xvar <- rlang::sym(xvar)
yvar <- rlang::sym(yvar)
p1 <-dat %>%
ggplot(aes(x = !!xvar, y = !!yvar)) +
geom_point()
return(p1)

}

fun(weather, xVariable, yVariable)

Sample Image

How to deal with spaces in column names?

This is a "bug" in the package ggplot2 that comes from the fact that the function as.data.frame() in the internal ggplot2 function quoted_df converts the names to syntactically valid names. These syntactically valid names cannot be found in the original dataframe, hence the error.

To remind you :

syntactically valid names consists of letters, numbers and the dot or
underline characters, and start with a letter or the dot (but the dot
cannot be followed by a number)

There's a reason for that. There's also a reason why ggplot allows you to set labels using labs, eg using the following dummy dataset with valid names:

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

You can use labs at the end to make this code work

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")

To produce

Sample Image



Related Topics



Leave a reply



Submit