2

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.

Sylvia Rodriguez
  • 1,203
  • 2
  • 11
  • 30
  • Possible duplicate https://stackoverflow.com/questions/20309876/r-how-to-replace-in-a-string You have to use it for column names instead of a vector. – Ronak Shah Aug 25 '20 at 00:33

2 Answers2

3

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")
MrFlick
  • 195,160
  • 17
  • 277
  • 295
2

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.

morrowcj
  • 169
  • 6