資源描述:
《R語言數(shù)據(jù)存儲與讀取.docx》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在工程資料-天天文庫。
1、檢索:write.tablewrite.csv區(qū)別?不寫入行名?row.names?不寫入列名?col.names>write.table(x,file="mydata",row.names=FALSE,col.names=FALSE)?#可以>write.csv(x,file="mydata2",row.names=FALSE,col.names=FALSE)?#不可以1.?首先用getwd()獲得當(dāng)前目錄,用setwd("C:/data")設(shè)定當(dāng)前目錄:2.0數(shù)據(jù)保存:創(chuàng)建數(shù)據(jù)框d:?>d<-da
2、ta.frame(obs=c(1,2,3),treat=c("A","B","A"),?weight=c(2.3,NA,9))2.1保存為簡單文本:>write.table(d,file="c:/data/foo.txt",?row.names=F,quote=F)2.2?保存為逗號分割文本:>write.csv(d,file="c:/data/foo.csv",?row.names=F,quote=F)2.3?保存為R格式文件:>save(d,file="c:/data/foo.Rdata")2.4
3、保存工作空間鏡像:?>save.image()=?save(list=ls(all=TRUE),file=".RData")3.0數(shù)據(jù)讀取:讀取函數(shù)主要有:read.table(),scan(),read.fwf().3.1用?read.table()讀"c:data”?下houses.dat:>setwd("C:/data");?HousePrice<-read.table(file="houses.dat")?如果明確數(shù)據(jù)第一行做表頭,則使用header選項:>HousePrice<-read.
4、table("houses.dat",header=TRUE)read.table()變形有:?aread.csv(),read.csv2(),read.delim(),read.delim2().前兩讀取逗號分割數(shù)據(jù),后兩個讀取其他分割符數(shù)據(jù)。3.2?用scan()比read.table()更靈活。但要指定變量類型:如:C:datadata.dat:M65168M70172F54156F58163>mydata<-scan("data.dat",what=list("",0,0))?>mydat
5、a<-scan("data.dat",?what=list(Sex="",Weight=0,Height=0))3.3用read.fwf()讀取文件中一些固定寬度數(shù)據(jù):如:C:datadata.txt:A1.501.2A1.551.3B1.601.4>mydata<-read.fwf("data.txt",widths=c(1,4,3),?col.names=c("X","Y","Z"))4.0excel格式數(shù)據(jù)讀?。?.1利用剪切板:選擇excel數(shù)據(jù),再用(CTRL+C)復(fù)制。在R中鍵入命令:
6、>mydata<-read.delim("clipboard")4.2使用程序包?RODBC.如:?c:databody.xlsSexWeightHeightM65168M70172F54156F58163>library(RODBC)>z<-odbcConnectExcel("c:/data/body.xls")>foo<-sqlFetch(z,"Sheet1")>close(z)