R語言學(xué)習(xí)5
訪問變量和處理數(shù)據(jù)子集
- 訪問數(shù)據(jù)框
seywd(“C:/RBOOK/”)
Squid<-read.table(file=”Squid.txt”,header=TRUE)#讀取Squid.txt
names(Squid)#讀取Squid中的變量
[1] ”Sample””Year””Month””Location””Sex””GSI”
str(Squid)#Squid中的變量屬性
‘data.frame’:2644 obs.of 6 variables:
$ Sample : int 1 2 3 4
$ Year :int 1 1 1 1
$ Month : int 1 1 1 2
$ Location : int 1 2 1 3
$ Sex : int 2 2 2 2
$ GSI :num 10.44 12.33 14.03 9.30
setwd(“C:/RBOOK/”)
Squid2<-read.table(file=”Squid.txt”,dec=”,”,header=TRUE)#分隔符是逗號
- 函數(shù)中的數(shù)據(jù)參數(shù)
M1<-lm(GSI~factor(Location)+factor(Year),data=Squid)#線性回歸函數(shù)模型摇庙,不是所
函數(shù)支持data選項伸刃。
mean(GSI,data=Squid)#不支持data選項肴焊。
boxplot(GSI~factor(Location),data=Squid)#函數(shù)中沒有data參數(shù)府寒。
Squid$GSI#訪問GSI變量割卖。
Squid[,6]#訪問第六列數(shù)據(jù)。
mean(Squid$GSI)#計算GSI的平均值三幻。
- 訪問數(shù)據(jù)子集
Squid$Sex
unique(Squid$Sex)#這個變量里有多少個唯一值邢隧。
Sel<-Squid$Sex==1
SquidM<-Squid[Sel,]
SquidM#輸出性別為雄性的數(shù)據(jù)
SquidM<-Squid[Squid$Sex==1,]
SquidM#簡寫
Squid<-Squid[Squid$Location==1|Squid$Location==2|Squid$Location==4,]#Location為1,2隶糕,4的數(shù)據(jù)瓷产。
SquidM.1<-Squid[Squid$Sex==1&Squid$Location==1,]#性別為雄性,地址為1的數(shù)據(jù)枚驻。
<0 rows>(or 0-length row.names)#對應(yīng)的測量值為0濒旦。
Ordl<-order(Squid$Month)
Squid[Ordl,]#根據(jù)月份由低到高的值排列GSI數(shù)據(jù)。
Squid$GSI[Ord1]#只顯示GSI的排列再登。
4.組合數(shù)據(jù)集
>Setwd(“C:/RBOOK/”)
>Sq1<read.table(file=”squid1.txt”,header=TRUE)
>Sq2<read.table(file=”squid2.txt”,header=TRUE)
>SquidMerged<-merge(Sq1,Sq2,by=”Sample”)
>SquidMerged#依據(jù)Sample將兩個表格組合尔邓。
>SquidMerged<-merge(Sq1,Sq2,by=”Sample”,all=TRUE)
>SquidMerged#Sq1里沒有的,Sq2里出現(xiàn)的數(shù)據(jù)霎冯,用NA填充铃拇。
5.輸出數(shù)據(jù)
>SquidM<-Squid[Squid$Sex==1,]
>write.table(SquidM,file=”MaleSquid.txt”,sep=””,quote=FALSE,append=False,na=”NA”)
Ascii文件,quote=FALSE消除字符串(標(biāo)題)的引號標(biāo)志钞瀑,na=”NA”允許缺失值由什么來替代沈撞,append=FALSE打開一個新的文件。
6.重新編碼分類變量
>Str(Squid)
>Squid$fSex<-factor(Squid$Sex)
>Squid$fSex<-factor(Squid$Sex,levels=c(1,2),labels=c(“M”,”F”))
>Squid$fSex#性別1雕什,2換為M缠俺,F(xiàn)显晶。
>boxplot(GSI~fSex,data=Squid)
>M1<-lm(GSI~fSex+fLocation,data=Squid)#畫箱圖和線性規(guī)劃。SSS