您的位置:首页 > 其它

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

2016-05-31 15:55 483 查看
1、读取数据
lesson8.txt文件放在工作目录下
方法1:使用read.table
参考这个帖子:http://f.dataguru.cn/thread-208388-1-1.html
w=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.html
Sys.setlocale("LC_TIME", "C") 是时间显示设置,类似打date format;strptime是文本型转日期型函数
Sys.setlocale("LC_TIME", "C")   #时间显示设置为C语言
a=readLines("lesson8.txt")
a=na.omit(a)  #去除NA
dim(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.html
x=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和strptime
date=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))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: