Home > front end >  Replace characters in the middle of a string
Replace characters in the middle of a string

Time:11-09

I have the following df

df <- data.frame(name.name1 = c(1, 1, 1),
                 name.name2 = c(2, 2, 2),
                 name.name3 = c(3, 3, 3))

I'm trying to substitute . by space. When I do

colnames(df) <- gsub("^.$", " ", colnames(df))

What's happening here and how can I proceed?

CodePudding user response:

Go back one step and avoid them in the first place, using check.names argument:

#when creating a dataframe
data.frame("name name1" = c(1, 1, 1),
           "name name2" = c(2, 2, 2),
           "name name3"= c(3, 3, 3), check.names = FALSE)
#   name name1 name name2 name name3
# 1          1          2          3
# 2          1          2          3
# 3          1          2          3

#when importing data from file
read.table("myFile.txt", header = TRUE, check.names = FALSE)

CodePudding user response:

You need to escape the dot with double back slash like so

colnames(df) <- gsub("\\.", " ", colnames(df))

Output:

"name name1" "name name2" "name name3"
  • Related