我必须编写自己的函数来绘制二项分布的密度函数,因此当n = 20和p = 0.1,0.2,...,0.9时绘制适当的图形.我还需要对图表进行评论.
我试过这个;
graph <- function(n,p){
x <- dbinom(0:n,size=n,prob=p)
return(barplot(x,names.arg=0:n))
}
graph(20,0.1)
graph(20,0.2)
graph(20,0.3)
graph(20,0.4)
graph(20,0.5)
graph(20,0.6)
graph(20,0.7)
graph(20,0.8)
graph(20,0.9)
#OR
graph(20,scan())
Run Code Online (Sandbox Code Playgroud)
我的第一个问题:graph(20,p)除了使用之外,有什么方法可以让我多次写下这行scan()?
我的第二个问题:
我希望在一个设备中看到图表,或者想点击ENTER查看下一个图表.我写
par(mfcol=c(2,5))
graph(20,0.1)
graph(20,0.2)
graph(20,0.3)
graph(20,0.4)
graph(20,0.5)
graph(20,0.6)
graph(20,0.7)
graph(20,0.8)
graph(20,0.9)
Run Code Online (Sandbox Code Playgroud)
但图表太小了.我怎么能很好地呈现图表,给出头线n = 20和p =我用来绘制图形的值?[尽管可以通过mtext()在调用函数后写入来完成graph但是这样做我必须编写类似的几行倍.所以我想在功能上做到这一点graph.]
我的上一个问题:
关于评论.图表显示,随着成功的概率,p正在增加图表趋于正确,即图表是正确的倾斜.
有没有办法对图表进行评论program?
我必须编写以下方法的函数:
拒绝方法(统一信封):
假设fx仅在[a,b]和fx≤k上非零.
独立于X生成X~U(a,b)和Y~U(0,k)(因此P =(X,Y)均匀分布在矩形[a,b]×[0,k])上.
如果Y <fx(x)则返回X,否则返回步骤1.
rejectionK <- function(fx, a, b, K) {
# simulates from the pdf fx using the rejection algorithm
# assumes fx is 0 outside [a, b] and bounded by K
# note that we exit the infinite loop using the return statement
while (TRUE) {
x <- runif(1, a, b)
y <- runif(1, 0, K)
if (y < fx(x)) return(x)
}
}
Run Code Online (Sandbox Code Playgroud)我不明白这是为什么TRUE在 while (TRUE)?
如果(y <fx(x))不为真,则该方法建议再次重复循环以再次生成统一数.(y <fx(x))不为真=假.那么为什么不是条件while (FALSE) …
假设我有以下数据框
set.seed(36)
n <- 300
dat <- data.frame(x = round(runif(n,0,200)), y = round(runif(n, 0, 500)))
d <- dat[order(dat$y),]
Run Code Online (Sandbox Code Playgroud)
对于每个值d$y<=300,我必须创建一个变量res,其中分子是指标的总和,(d$x <= d$y[i])而分母是指标的总和(d$y >= d$y[i]).我写的代码是for loop:
res <- NULL
for( i in seq_len(sum(d$y<=300)) ){
numerator <- sum(d$x <= d$y[i])
denominator <- sum(d$y >= d$y[i])
res[i] <- numerator / denominator
}
Run Code Online (Sandbox Code Playgroud)
但我担心的是当观察数量x和y数量很大时,即数据帧的行数增加时,for loop将会缓慢地工作.另外,如果我模拟数据1000次并且每次运行for loop,程序将是低效的.
什么是更有效的代码解决方案?
当我运行该命令时plot(qnorm),它会生成以下图表:

但我不明白该命令如何产生图形?
我有一个数据,从2007年7月1日到2014年10月5日.
我正在尝试创建一个名为month_index数据框的列,该列dat将随着年和月的增加而增加整数值.
我写了下面的R代码,但它看起来并不简约.
dat$month_index <- with(dat,
ifelse(Year == 2007 & Month == 7, 7,
ifelse(Year == 2007 & Month == 8, 8,
ifelse(Year == 2007 & Month == 9, 9,
ifelse (Year == 2007 & Month == 10, 10,
ifelse(Year == 2007 & Month == 11, 11,
ifelse(Year == 2007 & Month == 12, 12,
ifelse(Year == 2008 & Month == 1, 13,
ifelse(Year == 2008 & Month == 2, 14,
ifelse(Year == 2008 & Month …Run Code Online (Sandbox Code Playgroud)