How to replace the “.” in column names generated by read.csv() with a single space when exporting?

拥有回忆 提交于 2019-11-30 11:57:55

问题


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.


回答1:


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.




回答2:


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).




回答3:


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)



回答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"


来源:https://stackoverflow.com/questions/17152483/how-to-replace-the-in-column-names-generated-by-read-csv-with-a-single-spa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!