0
votes

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"  
1
No, names of objects in R cannot contain spaces!PaulS
@PaulS, column names can contain spaces, but it's rarely desirable.jdobres
I agree with comments here. A better practice would be to replace with underscore i.e. _Sweepy Dodo
@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

1 Answers

3
votes

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`