一些函數

1set.seed()

用于設定隨機數種子,一個特定的種子可以產生一個特定的偽隨機序列,這個函數的主要目的,是讓你的模擬能夠可重復出現,因為很多時候我們需要取隨機數,但這段代碼再跑一次的時候,結果就不一樣了,如果需要重復出現同樣的模擬結果的話,就可以用set.seed()。在調試程序或者做展示的時候,結果的可重復性是很重要的,所以隨機數種子也就很有必要。
也可以簡單地理解為括號里的數只是一個編號而已,例如set.seed(100)不應將括號里的數字理解成“一百”,而是應該理解成“編號為一零零的隨機數發(fā)生”,下一次再模擬可以采用二零零(200)或者一一一(111)等不同的編號即可,編號設定基本可以隨意。

>x<-rnorm(10) #隨機生成10個隨機數 
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) #再次隨機生成10個隨機數 
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) #設定種子 
x<-rnorm(10) # 在設定種子的前提下生成10個隨機數 
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) # 設定種子 
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水平合并兩數據框,即添加列

# 根據id合并兩數據框
total <- merge(data frameA,data frameB,by="ID")

# 根據id和country合并兩數據框
total <- merge(data frameA,data frameB,by=c("ID","Country"))

4.2垂直合并兩數據框,即添加行

total <- rbind(data frameA, data frameB)

If data frameA has variables that data frameB does not, then either:

  1. Delete the extra variables in data frameA or
  2. 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 轉置函數t()

使用t()函數來轉置矩陣或數據幀。
行名變成了變量(列)名。

  mtcars
t(mtcars)  #行名轉變成列名

7 melt()

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

mdata

8 cast

cast(data, formula, function) 

我覺得很少用到吧,類似刪除重復,先不列了


9

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容