Specifying column names in a data.frame changes spaces to "."

Brandon Bertelsen picture Brandon Bertelsen · Aug 5, 2010 · Viewed 35.7k times · Source

Let's say I have a data.frame, like so:

x <- c(1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10,1:10)
df <- data.frame("Label 1"=x,"Label 2"=rnorm(100))

head(df,3)

returns:

  Label.1    Label.2
1       1  1.9825458
2       2 -0.4515584
3       3  0.6397516

How do I get R to stop automagically replacing the space with a period in the column name? ie, "Label 1" instead of "Label.1".

Answer

Brandon Bertelsen picture Brandon Bertelsen · Aug 5, 2010

You may set check.names = FALSE in data.frame (as well as in read.table):

df <- data.frame("Label 1" = 1:3, "Label 2" = rnorm(3), check.names = FALSE)

returns:

  Label 1    Label 2
1       1  0.2013347
2       2  1.8823111
3       3 -0.5233811

From ?data.frame:

check.names
logical. If TRUE then the names of the variables in the data frame are checked to ensure that they are syntactically valid variable names and are not duplicated. If necessary they are adjusted (by make.names) so that they are.


From ?make.names:

A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number. Names such as ".2way" are not valid, and neither are the reserved words.

All invalid characters are translated to "."


Also, if you need to subset a variable with an 'invalid' name using $, you can use backticks `. For example:

df$`Label 1`