R語(yǔ)言學(xué)習(xí)5
訪問(wèn)變量和處理數(shù)據(jù)子集
- 訪問(wèn)數(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)#分隔符是逗號(hào)
- 函數(shù)中的數(shù)據(jù)參數(shù)
M1<-lm(GSI~factor(Location)+factor(Year),data=Squid)#線性回歸函數(shù)模型,不是所
函數(shù)支持data選項(xiàng)。
mean(GSI,data=Squid)#不支持data選項(xiàng)。
boxplot(GSI~factor(Location),data=Squid)#函數(shù)中沒(méi)有data參數(shù)。
Squid$GSI#訪問(wèn)GSI變量。
Squid[,6]#訪問(wèn)第六列數(shù)據(jù)。
mean(Squid$GSI)#計(jì)算GSI的平均值。
- 訪問(wèn)數(shù)據(jù)子集
Squid$Sex
unique(Squid$Sex)#這個(gè)變量里有多少個(gè)唯一值。
Sel<-Squid$Sex==1
SquidM<-Squid[Sel,]
SquidM#輸出性別為雄性的數(shù)據(jù)
SquidM<-Squid[Squid$Sex==1,]
SquidM#簡(jiǎn)寫(xiě)
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)#對(duì)應(yīng)的測(cè)量值為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將兩個(gè)表格組合。
>SquidMerged<-merge(Sq1,Sq2,by=”Sample”,all=TRUE)
>SquidMerged#Sq1里沒(méi)有的,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)題)的引號(hào)標(biāo)志,na=”NA”允許缺失值由什么來(lái)替代,append=FALSE打開(kāi)一個(gè)新的文件。
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)#畫(huà)箱圖和線性規(guī)劃。SSS