|||
第一章
对UFO报告数据的处理
R程序说明如下:
library(ggplot2)
##读入文件,不对string进行factor转换,将空字符设置为NA
ufo<-read.delim("ufo_awesome.tsv",sep="t",stringsAsFactors=FALSE,header=FALSE,na.strings="")
##查看前五组数据
head(ufo)
##对列进行重命名
names(ufo)<-c("DateOccurred","DateReported","Location","ShortDescription","Duration","LongDescription")
问题一(删除不规范样本)
##希望将string格式转换为日期格式出现错误
ufo$DateOccurred<-as.Date(ufo$DateOccurred,format="%Y%m%d")
错误于strptime(x, format, tz = "GMT") : 输入字符串太长
##输出前五组不符合日期格式的数据
head(ufo[which(nchar(ufo$DateOccurred)!=8|nchar(ufo$DateReported)!=8),1])
##标记错误数据
good.rows<-ifelse(nchar(ufo$DateOccurred)!=8|nchar(ufo$DateReported)!=8,FALSE,TRUE)
##统计错误数据个数
length(which(!good.rows))
[1] 731
length(which(good.rows))
[1] 61139
get.location<-function(l){
##按“,”分割字符串
split.location<-tryCatch(strsplit(l,",")[[1]],error=function(e) return(c(NA,NA)))
##正则表达式去除前面的空格
clean.location<-gsub("^","",split.location)
if(length(clean.location)>2){
return(c(NA,NA))
}else{
return(clean.location)
}
}
##用写好的get.location方法清洗地点数据
city.state<-lapply(ufo$Location,get.location)
读到了P23。主要工作包括下载了数据资料;对数据的导入;查看前后5行信息了解数据大致内容
对不符合格式的数据的处理方法,首先确定这些数据的数量,如果数量较少就直接删除
然后整理地点数据,这里用到正则表达式,花了一天的时间系统的学习了一下,受益匪浅。
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-6-2 22:11
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社