在R中使用readLines()时的歧义

时间:2016-09-14 16:50:07

标签: r csv

我的数据集的第一行包含列的名称。 它看起来像这样 -

#"State Code","County Code","Site Num","Parameter Code","POC","Latitude","Longitude","Datum","Parameter Name","Sample Duration","Pollutant Standard","Metric Used","Method Name","Year","Units of Measure","Event Type","Observation Count","Observation Percent","Completeness Indicator","Valid Day Count","Required Day Count","Exceptional Data Count","Null Data Count","Primary Exceedance Count","Secondary Exceedance Count","Certification Indicator","Num Obs Below MDL","Arithmetic Mean","Arithmetic Standard Dev","1st Max Value","1st Max DateTime","2nd Max Value","2nd Max DateTime","3rd Max Value","3rd Max DateTime","4th Max Value","4th Max DateTime","1st Max Non Overlapping Value","1st NO Max DateTime","2nd Max Non Overlapping Value","2nd NO Max DateTime","99th Percentile","98th Percentile","95th Percentile","90th Percentile","75th Percentile","50th Percentile","10th Percentile","Local Site Name","Address","State Name","County Name","City Name","CBSA Name","Date of Last Change"

这是一个csv文件。 由于我使用的是Windows,我写了

pm0 <-read.csv("C:/Users/Ad/Desktop/EDA/2010.csv",
                comment.char="#", header=FALSE, sep=",", na.strings="")

读取除第一行之外的此csv文件。现在我想读取第一行,以便我可以使用第一行来设置生成的数据框的列名。为此,我写了 -

cnames<-readLines("C:/Users/Ad/Desktop/EDA/2010.csv",1)

但是当我打印cnames时,我得到了这个 -

[1] "\"State Code\",\"County Code\",\"Site Num\",\"Parameter Code\",\"POC\",\"Latitude\",\"Longitude\",\"Datum\",\"Parameter Name\",\"Sample Duration\",\"Pollutant Standard\",\"Metric Used\",\"Method Name\",\"Year\",\"Units of Measure\",\"Event Type\",\"Observation Count\",\"Observation Percent\".

我不明白为什么\会在cnames的每个元素的开头和结尾出现。

有人可以帮我删除。

2 个答案:

答案 0 :(得分:1)

这是来自Coursera的探索性数据分析(EDA)任务,对吗?我相信你符合荣誉准则。

'cnames'中包含的是一个用双引号括起来的字符串,其中反斜杠操作符已经转义了其他引号。

要解决这个问题,请尝试:

cnames1 <- strsplit(cnames, ",")
gsub("[\"]", "", cnames1[[1]], perl=TRUE)

这给出了一系列名称。

[1] "State Code"          "County Code"         "Site Num"           
 [4] "Parameter Code"      "POC"                 "Latitude"           
 [7] "Longitude"           "Datum"               "Parameter Name"     
[10] "Sample Duration"     "Pollutant Standard"  "Metric Used"        
[13] "Method Name"         "Year"                "Units of Measure"   
[16] "Event Type"          "Observation Count"   "Observation Percent"

答案 1 :(得分:0)

我做的是这个 -

pm0<-read.csv("C:/Users/Ad/Desktop/EDA/2010.csv",comment.char="#",header=TRUE,sep=",",na.strings="")

现在,对象pm0包含第一行csv文件作为列名。