繁体   English   中英

R-Studio 中的条件

[英]Conditions in R-Studio

我有这个问题陈述,我以这个为例:

Product_id  product_type    views   inventory
1   producttype1    Y   Y
2   producttype2    N   N
3   producttype3    Y   Y
4   producttype4    N   N
5   producttype5    Y   Y
6   producttype6    N   N
7   producttype7    Y   Y
8   producttype1    N   N
9   producttype2    Y   Y
10  producttype3    N   N
11  producttype4    Y   Y
12  producttype5    N   N
13  producttype6    Y   Y
14  producttype7    N   N
15  producttype7    Y   Y

我有 1000 万人口,我试图从中提取 10% 的人口样本,我必须按 product_type、views 对它们进行分组。 但最终当我得到样本时,如果样本小于 500k,那么我可以保持原样,但在样本最高高于 500k 的情况下,我必须将样本减少到 500k。 这是我为分组和提取 10% 样本而编写的代码:

MPSSAMPLE %>% 
  group_by(product_type, views) %>%
  sample_frac(.10) -> sampledData

任何人都可以帮我解决条件吗?

您可以使用min获得该组样本总体的 500k 或 10% 之间的最小值。

library(dplyr)

n <- 500000

MPSSAMPLE %>% 
  group_by(product_type, views) %>%
  sample_n(min(n() * 0.1, n)) -> sampledData

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM