请教一道R语言的统计题。。急T^T在线等

Python019

请教一道R语言的统计题。。急T^T在线等,第1张

fun<-function(n){

times=1000#模拟次数

none=0

over=0

sum=0

for(i in 1:times){

A=1:n #代表1到n号人

B=1:n #代表1到n号帽

num=0#有num个人得到自己的帽子

max=n

for(j in 1:n-1){

rand=round(runif(2,min=1,max=max)) #产生2个随机数,取整

people=rand[1]

hat=rand[2]

if(A[people]==B[hat]){

num=num+1

}

A<-A[-people] #删除走的人

B<-B[-hat] #删除掉已拿走的帽子

max=max-1 #随机数最大值减一

}

if(num==0)none=none+1

if(num>0)over=over+1

sum=sum+num/n

}

c(

over/times, #至少有1个人拿到了自己帽子的概率

none/times, #没有一个人拿到自己帽子的概率

sum/times #得到自己帽子的概率

)

}

我就用ggplot2包来做吧,逼格高一点。。。o(╯□╰)o

我是把所有行都放在一个图里,用颜色来区别行数。有更多要求就再问(希望不是太麻烦。。。)

要先安装ggplot2,可以在联网状态下输入install.packages("ggplot2")自动安装。

假设你的矩阵变量名为matrix

d<-dim(matrix)

y<-as.numeric(t(matrix))

row<-factor(rep(1:d[1],each=d[2]))

x<-rep(1:d[2],times=d[1])

data<-data.frame(y=y,x=x,row=row)

library(ggplot2)

ggplot(data=data,aes(x=x,y=y,group=row,color=row))+geom_line()