使用条件概率提取特定范围值的数据框

Data frames using conditional probabilities to extract a certain range of values

我需要一些帮助来回答以下问题:

Dr Barchan makes 600 independent recordings of Eric’s coordinates (X, Y, Z), selects the cases where X ∈ (0.45, 0.55), and draws a histogram of the Y values for these cases.

By construction, these values of Y follow the conditional distribution of Y given X ∈ (0.45,0.55). Use your function sample3d to mimic this process and draw the resulting histogram. How many samples of Y are displayed in this histogram?

We can argue that the conditional distribution of Y given X ∈ (0.45, 0.55) approximates the conditional distribution of Y given X = 0.5 — and this approximation is improved if we make the interval of X values smaller.

Repeat the above simulations selecting cases where X ∈ (0.5 − δ, 0.5 + δ), using a suitably chosen δ and a large enough sample size to give a reliable picture of the conditional distribution of Y given X = 0.5.

我知道在第一段中我们希望为我们在 sample3d(600) 中得到的 x、y、z 生成值,然后将 x 限制在 0.45-0.55 范围内,有没有办法编写代码(也许是一个 if 函数),让我将 x 的值保持在这个范围内,但丢弃所有不在该范围内的 600 中的 x?还有没有人对第三段中的条件概率位有任何提示。

sample3d = function(n)
{
  df = data.frame() 

  while(n>0)
  {
    X = runif(1,-1,1) 
    Y = runif(1,-1,1)
    Z = runif(1,-1,1)
    a = X^2 + Y^2 + Z^2 

    if( a < 1 ) 

    {
      b = (X^2+Y^2+Z^2)^(0.5) 

      vector = data.frame(X = X/b, Y = Y/b, Z = Z/b) 
      df = rbind(vector,df)
      n = n- 1
    }
  }
  df
}
sample3d(n)

任何帮助将不胜感激,谢谢。

您的函数生成一个数据框。问题中要求您在给定范围内的数据框中找到那些值的部分可以通过过滤数据框来解决。请注意,您正在寻找闭区间(不包括值)。

df <- sample3d(600)
df[df$X > 0.45 & df$X < 0.55,]

注意逗号。

您也可以使用 dplyr 解决方案,但不要使用助手 between(),因为它会查看开区间(您需要闭区间)。

filter(df, X > 0.45 & X < 0.55)

对于剩余的作业,看看您能找出什么,如果您 运行 遇到特定问题,堆栈溢出可以帮助您。