Names of columns change from CSV to R: dot instead of slash

狂风中的少年 提交于 2021-01-27 19:30:50

问题


When I inport a CSV file in R the names of the columns change. They go from "Fe/Cu" to "Fe.Cu". But I have this mysterious problem only with one CSV file. I tried to rename the columns

colnames(a[12:ncol(a)])=c("Fe/Cu","Fe/Zn","Fe/Ba")

But nothing happens. Any ideas?


回答1:


Adding check.names=FALSE to csv.read function call will allow you to get the original names. This is because by default csv.read will check if column names are syntactically valid as stated by @Asayat in the commets.

From csv.read documentation:

check.names - logical: If TRUE then the names of the variables in the data frame are checked to ensure that they are syntactically valid variable names. If necessary they are adjusted (by make.names) so that they are, and also to ensure that there are no duplicates.

If you then check for the documentation of make.names you will find:

A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number. Names such as ".2way" are not valid, and neither are the reserved words.

which is what @Asayat commented.




回答2:


Column indexes should be after colnames like below:

colnames(a)[12:ncol(a)]=c("Fe/Cu","Fe/Zn","Fe/Ba")


来源:https://stackoverflow.com/questions/43999260/names-of-columns-change-from-csv-to-r-dot-instead-of-slash

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