Milind Kumar
Milind Kumar

Reputation: 189

Error when ggplot variable/column name has spaces

I read a table. Put the columns names into it. Then I and then Plot the graph with the help of GGplot. I gets error when in aes parameter in ggplot I use names with a space in between like " shucked weight" as shown in code but the code runs and graph is plotted if I use single letter parameter like "wweight". When I replaced column name of "shucked weight" to "sweight" , I got the graph without an error.

This is quite unusual error that I have noticed and I am not able to figure out why?

library(data.table)
a<-fread("https://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data",sep=",")
dim(a)
names(a)<-c("sex","length","diameter","height","wweight","shucked weight","viscera Weight","shell weight","rings")
g<-ggplot(data = a,aes(wweight,rings))
g+geom_point()+geom_smooth(method="lm")
g<-ggplot(data = a,aes(shucked weight,rings))
g+geom_point()+geom_smooth(method="lm")

Error statement after Execution :

Error: unexpected symbol in "g<-ggplot(data = a,aes(shucked weight"

Upvotes: 2

Views: 1360

Answers (1)

Roman
Roman

Reputation: 4989

Answered in comments:

If variable names include spaces or other special characters you need to surround them with backticks:

g <-ggplot(data = a, aes(`shucked weight`, rings)) + 
    geom_point() + 
    geom_smooth(method = "lm")

Upvotes: 2

Related Questions