R读取数据_转换时间_可视化实例

来源:互联网 发布:中国2016年m2数据 编辑:程序博客网 时间:2024/05/01 22:32
1、读取数据lesson8.txt文件放在工作目录下方法1:使用read.table参考这个帖子:http://f.dataguru.cn/thread-208388-1-1.htmlw=read.table("lesson8.txt",sep="\t")y<-matrix(as.matrix(w),nrow(w)/3,3,byrow=TRUE)y<-as.data.frame(y)colnames(y)<-c("time","ip","pv")ip=as.numeric(y$ip)pv=as.numeric(y$pv)tmp<-read.table("lesson8.txt",sep="\t")data<-matrix(as.matrix(tmp),nrow(tmp)/3,3,byrow=TRUE)colnames(data)<-c("time","ip","pv")方法2:使用readlines参考这个帖子:http://f.dataguru.cn/thread-208527-1-1.htmlSys.setlocale("LC_TIME", "C") 是时间显示设置,类似打date format;strptime是文本型转日期型函数Sys.setlocale("LC_TIME", "C")   #时间显示设置为C语言a=readLines("lesson8.txt")  a=na.omit(a)  #去除NAdim(a)=c(3,83)  #gsub("HKT","",a[1,])  替换a[1,]里的HKT为空ip=as.numeric(a[2,]);pv=as.numeric(a[3,]) date=as.Date(gsub("HKT","",a[1,]), "%a %b %d %H:%M:%S %Y")library(ggplot2)qplot(x=date,y=ip/pv,geom=c("line"),color=date)方法3:使用scan参考这个帖子:http://f.dataguru.cn/thread-208471-1-1.htmlx=scan("lesson8.txt",sep="\n",what=list("","",""))data=data.frame('date'=as.character(c(x[1],recursive= TRUE)),            'ip'=as.numeric(c(x[2],recursive = TRUE)),            'pv'=as.numeric(c(x[3],recursive = TRUE)))最后的结果是得到data.frame格式的数据2、转换数据输入example(as.Date),就可以看到如下命令,这段命令帮助转换时间格式:lc <- Sys.getlocale("LC_TIME")Sys.setlocale("LC_TIME","C")对于时间数据格式,转换时一定要准确,否则会转换成“NA”方法:使用as.Date和strptimedate=as.Date(strptime(data[,1], "%a %b%d %H:%M:%S HKT %Y"))对于另外的ip和pv数据,使用as.numeric转换ip=as.numeric(data[,2])pv=as.numeric(data[,3])3、画图library(ggplot2)(1)画pv随时间变化qplot(date, pv,geom =c("line","point"), main="pv line",xlab ="Date", ylab = "pv")(2)画ip随时间变化qplot(date, ip,geom =c("line","point"), main="ip line",xlab ="Date", ylab = "ip")(3)画pv/ip随时间变化qplot(date, pv/ip,geom =c("line","point"), main="pv/ip line",xlab ="Date", ylab = "pv/ip")线性预测绘图model <- lme(height ~ age, data = Oxboys, random = ~ 1 + age | Subject)oplot <- ggplot(Oxboys, aes(age, height, group = Subject)) + geom_line()age_grid <- seq(-1, 1, length = 10)subjects <- unique(Oxboys$Subject)preds <- expand.grid(age = age_grid, Subject = subjects)preds$height <- predict(model, preds)oplot + geom_line(data = preds, colour = "#3366FF", size= 0.4)Oxboys$fitted <-predict(model)Oxboys$resid <-with(Oxboys, fitted- height)oplot %+% Oxboys +aes(y = resid) +geom_smooth(aes(group=1))model2 <- update(model,height ~ age + I(age ^ 2))Oxboys$fitted2 <-predict(model2)Oxboys$resid2 <-with(Oxboys, fitted2 -height)oplot %+% Oxboys + aes(y =resid2) +geom_smooth(aes(group=1))

0 0
原创粉丝点击