Avoid that space in column name is replaced with period (".") when using read.csv()
Asked Answered
G

4

24

I am using R to do some data pre-processing, and here is the problem that I am faced with: I input the data using read.csv(filename,header=TRUE), and then the space in variable names became ".", for example, a variable named Full Code became Full.Code in the generated dataframe. After the processing, I use write.xlsx(filename) to export the results, while the variable names are changed. How to address this problem?

Besides, in the output .xlsx file, the first column become indices(i.e., 1 to N), which is not what I am expecting.

Glycolysis answered 17/6, 2013 at 16:34 Comment(1)
You can avoid having to fix the names by calling read.csv with the option check.names=FALSE.Pooi
R
45

If your set check.names=FALSE in read.csv when you read the data in then the names will not be changed and you will not need to edit them before writing the data back out. This of course means that you would need quote the column names (back quotes in some cases) or refer to the columns by location rather than name while editing.

Richy answered 18/6, 2013 at 15:45 Comment(1)
I think using check.names=FALSE is a better choice than editing the column names, although re-reading the data includes lots of work for me. All in all, thanks for your answer! That really helps me lot.Glycolysis
D
11

To get spaces back in the names, do this (right before you export - R does let you have spaces in variable names, but it's a pain):

# A simple regular expression to replace dots with spaces
# This might have unintended consequences, so be sure to check the results
names(yourdata) <- gsub(x = names(yourdata),
                        pattern = "\\.",
                        replacement = " ")

To drop the first-column index, just add row.names = FALSE to your write.xlsx(). That's a common argument for functions that write out data in tabular format (write.csv() has it, too).

Despond answered 17/6, 2013 at 16:39 Comment(4)
Thanks a lot! The gsub() function works fine. But I still have a question: why should we use two escapes rather than simply using pattern="\."?Glycolysis
@zenotsang Good question - I'm not sure why R requires that.Despond
The first escape is used up when the R parser parses the string, this leaves a '\' for the regular expression. If you bypass the regular parser then you can get away with a single backslash (but that is probably more work than it is worth).Richy
I see. Obviously following the rules in R is better:)Thanks a lot!Glycolysis
B
4

Here's a function (sorry, I know it could be refactored) that makes nice column names even if there are multiple consecutive dots and trailing dots:

makeColNamesUserFriendly <- function(ds) {
  # FIXME: Repetitive.

  # Convert any number of consecutive dots to a single space.
  names(ds) <- gsub(x = names(ds),
                    pattern = "(\\.)+",
                    replacement = " ")

  # Drop the trailing spaces.
  names(ds) <- gsub(x = names(ds),
                    pattern = "( )+$",
                    replacement = "")
  ds
}

Example usage:

ds <- makeColNamesUserFriendly(ds)
Bisulcate answered 23/8, 2014 at 16:8 Comment(0)
P
4

Just to add to the answers already provided, here is another way of replacing the “.” or any other kind of punctation in column names by using a regex with the stringr package in the way like:

require(“stringr”)   
colnames(data) <- str_replace_all(colnames(data), "[:punct:]", " ")

For example try:

data <- data.frame(variable.x = 1:10, variable.y = 21:30, variable.z = "const")

colnames(data) <- str_replace_all(colnames(data), "[:punct:]", " ")

and

colnames(data)

will give you

[1] "variable x" "variable y" "variable z"
Presa answered 11/6, 2018 at 19:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.