R - How to replace "." (dot) with " (space) in the column names of a Data.Table?

Asked

Viewed 264 times

-1

I have an extended date.table with 64 columns.

The names of the columns are separated by points and I would like to separate by space.

Example:

Current: "Salary.January", "Salary.December", "Salary.Average"

I want: "Salary January", "Salary December", "Average Salary"

I know that the Names() function changes the column names and gsub() replaces the characters. However, I’m not sure how to apply this.

4 answers

1

Example 1 The first example shows how to change column names in a data table. This starts with the first column and goes up to the names you provided. For example, if there are eight columns in your data frame, but you provide only two names, only the first two columns will be renamed.

names(data) <- c("new_name", "another_new_name")

Example 2 The second example shows how to change the name of a column using the name to identify which column to apply the name to. The following code will rename the field old_name to new_name in the data frame called date.

# Rename a column in R
colnames(data)[colnames(data)=="old_name"] <- "new_name"

If you know the number of columns (quant_col) you can iterate and change the columns name dynamically as follows:

for(i in 1:quant_col) {
  names(data)[i]<-"new_name"
}
  • Yes, but in that case I would have to do column by column. I would not have a function to replace everything at once ?

  • @Ricardotheodoro

1

Just use gsub with the following regular expression: "\\.". Like the point "." is a metacharacter, you have to use the escape sequence with the two against bars.

nomes <- c("Salário.Janeiro", "Salário.Dezembro", "Salário.Médio")

nomes <- gsub("\\.", " ", nomes)
nomes
#[1] "Salário Janeiro"  "Salário Dezembro" "Salário Médio" 

However I do not recommend doing this, it is not usually a good idea to have spaces in the names of columns. There is nothing to gain (that I know) and can give problems.

  • Thanks ! That’s almost what I wanted. But I managed to solve, I was forgetting the " ." and using only "." ! Thanks.

  • About the recommendation, I understand. But that’s the format of the RAIS, so I chose to keep.

1


Worked out using:

names(df) <- gsub(pattern, replace, names(df))

In my case:

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

0

An option using the stringr package

str_replace(nomes,
            pattern = "\\.",
            replacement = " ")

[1] "Salário Janeiro"  "Salário Dezembro" "Salário Médio"  

Browser other questions tagged

You are not signed in. Login or sign up in order to post.