How to deal with spaces in column names?

You asked “Is there a better general approach to dealing with the problem of spaces (and other characters) in variable names” and yes there are a few:

  • Just don’t use them as things will break as you experienced here
  • Use the make.names() function to create safe names; this is used by R too to create identifiers (eg by using underscores for spaces etc)
  • If you must, protect the unsafe identifiers with backticks.

Example for the last two points:

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> 

Leave a Comment