Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing characters in column names

My data frame contains headers with dots, which I would like to replace with underscores.

Sample data:

myheaders = c("3.1","3.2","3.3","3.4","3.5","3.6")
mydata = c(2,0,3,1,1,4)
example = as.data.frame(t(mydata))
colnames(example) <- myheaders
example

> example
  3.1 3.2 3.3 3.4 3.5 3.6
1   2   0   3   1   1   4

Following a similar question, I’ve tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

myoutput <- data.frame(lapply(example, function(x) {gsub(".", "_", x, fixed = TRUE)}))

However, this just introduces "X" into the headers. Where is the mistake?

> myoutput
  X3.1 X3.2 X3.3 X3.4 X3.5 X3.6
1    2    0    3    1    1    4

This is my desired output:

> myoutput
   3_1  3_2  3_3  3_4  3_5   3_6
1    2    0    3    1    1    4

>Solution :

You want to change the column names, so should use colnames, otherwise you are applying the function to your data.frame (excluding column (or row) names).

colnames(example) <- gsub(".", "_", colnames(example), fixed = TRUE)
#   3_1 3_2 3_3 3_4 3_5 3_6
# 1   2   0   3   1   1   4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading