1set.seed()
用于设定随机数种子,一个特定的种子可以产生一个特定的伪随机序列,这个函数的主要目的,是让你的模拟能够可重复出现,因为很多时候我们需要取随机数,但这段代码再跑一次的时候,结果就不一样了,如果需要重复出现同样的模拟结果的话,就可以用set.seed()。在调试程序或者做展示的时候,结果的可重复性是很重要的,所以随机数种子也就很有必要。
也可以简单地理解为括号里的数只是一个编号而已,例如set.seed(100)不应将括号里的数字理解成“一百”,而是应该理解成“编号为一零零的随机数发生”,下一次再模拟可以采用二零零(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:
- 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 转置函数t()
使用t()函数来转置矩阵或数据帧。
行名变成了变量(列)名。
mtcars
t(mtcars) #行名转变成列名
7 melt()
mydata
library(reshape)
mdata <- melt(mydata, id=c("name")) #按照名字向下排
mdata
mdata
8 cast
cast(data, formula, function)
我觉得很少用到吧,类似删除重复,先不列了