Substitute multiple periods in all column names in R

Viewed 477

I have the following data.frame.

 df = data.frame(a.dfs.56=c(rep("a",8), rep("b",5), rep("c",7), rep("d",10)), 
      b.fqh.28=rnorm(30, 6, 2), 
      c.34.2.fgs=rnorm(30, 12, 3.5), 
      d.tre.19.frn=rnorm(30, 8, 3)
      )

How can I substitute all periods "." in the column names to have them become dashes "-"?

I am aware of options like check.names=FALSE when using read.table or data.frame, but in this case, I cannot use this.

I have also tried variations of the following posts, but they did not work for me.

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

How can I use gsub in multiple specific column in r

R gsub column names in all data frames within a list

Thank you.

2 Answers

You can use gsub for name replacement

names(df) <- gsub(".", "-", names(df), fixed=TRUE)

Note that you need fixed=TRUE because normally gsub expects regular expressions and . is a special regular expression character.

But be aware that - is a non-standard character for variable names. If you try to use those columns with functions that use non-standard evaluation, you will need to surround the names in back-ticks to use them. For example

dplyr::filter(df, `a-dfs-56`=="a")

gsub("\\.", "-", names(df)) is the regex (regular expressions) way. The . is a special symbol in regex that means "match any single character". That's why the fixed = TRUE argument is included in MrFlick's answer.

The \\ (escape) tells R that we wan't the literal period and not the special symbol that it represents.

Related