1set.seed()
用于設(shè)定隨機(jī)數(shù)種子,一個(gè)特定的種子可以產(chǎn)生一個(gè)特定的偽隨機(jī)序列,這個(gè)函數(shù)的主要目的,是讓你的模擬能夠可重復(fù)出現(xiàn),因?yàn)楹芏鄷r(shí)候我們需要取隨機(jī)數(shù),但這段代碼再跑一次的時(shí)候,結(jié)果就不一樣了,如果需要重復(fù)出現(xiàn)同樣的模擬結(jié)果的話,就可以用set.seed()。在調(diào)試程序或者做展示的時(shí)候,結(jié)果的可重復(fù)性是很重要的,所以隨機(jī)數(shù)種子也就很有必要。
也可以簡(jiǎn)單地理解為括號(hào)里的數(shù)只是一個(gè)編號(hào)而已,例如set.seed(100)不應(yīng)將括號(hào)里的數(shù)字理解成“一百”,而是應(yīng)該理解成“編號(hào)為一零零的隨機(jī)數(shù)發(fā)生”,下一次再模擬可以采用二零零(200)或者一一一(111)等不同的編號(hào)即可,編號(hào)設(shè)定基本可以隨意。
>x<-rnorm(10) #隨機(jī)生成10個(gè)隨機(jī)數(shù)
x
[1] 0.3897943 -1.2080762 -0.3636760 -1.6266727 -0.2564784 1.1017795 0.7557815
[8] -0.2382336 0.9874447 0.7413901
x<-rnorm(10) #再次隨機(jī)生成10個(gè)隨機(jī)數(shù)
x
[1] 0.08934727 -0.95494386 -0.19515038 0.92552126 0.48297852
-0.59631064 -2.18528684
[8] -0.67486594 -2.11906119 -1.26519802
set.seed(5) #設(shè)定種子
x<-rnorm(10) # 在設(shè)定種子的前提下生成10個(gè)隨機(jī)數(shù)
x
[1] -0.84085548 1.38435934 -1.25549186 0.07014277 1.71144087 -0.60290798 -0.47216639
[8] -0.63537131 -0.28577363 0.13810822
set.seed(5) # 設(shè)定種子
y<-rnorm(10)
y
[1] -0.84085548 1.38435934 -1.25549186 0.07014277 1.71144087
-0.60290798 -0.47216639
[8] -0.63537131 -0.28577363 0.13810822
x == y
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
原文鏈接:https://blog.csdn.net/vencent_cy/article/details/50350020
2 attach()、detach()
3 排序order
# sorting examples using the mtcars dataset
attach(mtcars)
# sort by mpg
newdata <- mtcars[order(mpg),]
# sort by mpg and cyl
newdata <- mtcars[order(mpg, cyl),]
#sort by mpg (ascending) and cyl (descending)
newdata <- mtcars[order(mpg, -cyl),]
detach(mtcars)
4 合并
4.1水平合并兩數(shù)據(jù)框,即添加列
# 根據(jù)id合并兩數(shù)據(jù)框
total <- merge(data frameA,data frameB,by="ID")
# 根據(jù)id和country合并兩數(shù)據(jù)框
total <- merge(data frameA,data frameB,by=c("ID","Country"))
4.2垂直合并兩數(shù)據(jù)框,即添加行
total <- rbind(data frameA, data frameB)
If data frameA has variables that data frameB does not, then either:
- Delete the extra variables in data frameA or
- Create the additional variables in data frameB and set them to NA (missing)
before joining them with rbind( ).
5 aggregate我并不知道是什么意思
# aggregate data frame mtcars by cyl and vs, returning means
# for numeric variables
attach(mtcars)
aggdata <-aggregate(mtcars, by=list(cyl,vs),
FUN=mean, na.rm=TRUE)
print(aggdata)
detach(mtcars)
6 轉(zhuǎn)置函數(shù)t()
使用t()函數(shù)來轉(zhuǎn)置矩陣或數(shù)據(jù)幀。
行名變成了變量(列)名。
mtcars
t(mtcars) #行名轉(zhuǎn)變成列名
7 melt()

mydata
library(reshape)
mdata <- melt(mydata, id=c("name")) #按照名字向下排
mdata

mdata
8 cast
cast(data, formula, function)
我覺得很少用到吧,類似刪除重復(fù),先不列了