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:
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