0

Suppose the next dataframe:

df <- data.frame("level.3.london"=seq(1,5), "level.2.bogota"=seq(1,5), "level"=seq(1,5))

Is it possible to replace . for an space over the dataframe column names? The idea is to get the next output:

names(df)

Console output:

[1] "level 3 london" "level 2 bogota" "level"  
AlSub
  • 1,384
  • 1
  • 14
  • 33
  • No, names of objects in R cannot contain spaces! – PaulS Feb 28 '22 at 20:50
  • Does this answer your question? [Replacing a string in column names in dataframe in R with grepl](https://stackoverflow.com/questions/42892322/replacing-a-string-in-column-names-in-dataframe-in-r-with-grepl) – zephryl Feb 28 '22 at 20:50
  • 2
    @PaulS, column names can contain spaces, but it's rarely desirable. – jdobres Feb 28 '22 at 20:52
  • Thanks, @jdobres, I have just learned that from your answer! I have been convinced of the contrary for years! – PaulS Feb 28 '22 at 20:55
  • 2
    I agree with comments here. A better practice would be to replace with underscore i.e. `_` – Sweepy Dodo Feb 28 '22 at 20:55
  • 1
    @PaulS even something like `my var <- 1:10` is valid, strangely enough. You just have to use backticks around the variable name (which I can't seem to get working in a comment). We're all learning today! – jdobres Feb 28 '22 at 20:57

1 Answers1

3

A regular expression and the names function should do what you want, but be warned that column names with spaces can be difficult to work with.

names(df) <- gsub('\\.', ' ', names(df))

If you want to reference those column names, you will need to enclose them in backticks:

df$`level 3 London`
jdobres
  • 11,339
  • 1
  • 17
  • 37