如何计算R中的概率

时间:2020-02-11 22:37:22

标签: r dplyr statistics tidyverse probability

嗨,我上了统计课,我们得到了一个数据集“ NHANES”,我们对其进行了过滤以过滤成年吸烟者->“ NHANES_adult”。

library(NHANES)
# create a NHANES dataset without duplicated IDs 
NHANES <-
  NHANES %>%
  distinct(ID, .keep_all = TRUE) 

NHANES_adult <- NHANES %>%
  filter(Age >= 18) %>%  # only include individuals 18 or older
  filter(SmokeNow != 'NA')  # drop any observations with NA for SmokeNow

我的教授问以下问题:

1b。现在,我们从NHANES_adult数据帧中抽取100个人的样本,并计算吸烟者的比例,并将其保存到名为p_smokers的变量中。

set.seed(12345)  # PROVIDED CODE - this will cause it to create the same
                 # random sample each time

sample_size = 100 # size of each sample

p_smokers <- NHANES_adult %>%
  sample(sample_size) %>%  # take a sample from the data frame [I think this is okay]
  ____(____ = ____(____)) %>% # compute the probability of smoking [This is the point at which I'm struggling to understand what one-line function fits these blank parameters.
  ____()  # extract the variable from the data frame [I believe this is the mutate() function?]

p_smokers

1 个答案:

答案 0 :(得分:0)

也许这就是您要寻找的。似乎您应该使用sample_n()而不是sample()。要在一行中找到比例,可以使用mean()

sample_size <- 100

NHANES_adult %>%
  sample_n(sample_size) %>%  
  summarize(p_smok = mean(SmokeNow == "Yes")) %>% 
  pull(p_smok) 
相关问题