## R：从钻石数据集中的每个切割质量中抽取100个随机价格？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (20)

``````install.packages("ggplot2")
library(ggplot2)
data("diamonds")
``````

``````diamonds\$price[ sample( diamonds\$cut, size=100, replace=FALSE )]
``````

`````` Test.1<-diamonds %>%
group_by(cut) %>%
sample_n(size = 100) %>%
count(price)
``````

### 2 个回答

``````library(ggplot2)
data(diamonds)

xy <- split(diamonds, f = diamonds\$cut)

xy <- lapply(xy, FUN = function(x) {
x[sample(1:nrow(x), 100), ]
})

xy <- do.call(rbind, xy)
table(xy\$cut)

Fair      Good Very Good   Premium     Ideal
100       100       100       100       100
``````

``````library(dplyr)
library(ggplot2)

diamonds %>%
group_by(cut) %>%
sample_n(size = 100)
#> # A tibble: 500 x 10
#> # Groups:   cut [5]
#>    carat cut   color clarity depth table price     x     y     z
#>    <dbl> <ord> <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#>  1  0.7  Fair  D     SI2      65.6    55  2167  5.59  5.5   3.64
#>  2  1.01 Fair  E     SI1      64.8    58  4480  6.34  6.29  4.09
#>  3  0.7  Fair  G     VS1      65.2    57  2290  5.56  5.52  3.61
#>  4  0.7  Fair  F     I1       65.4    59   992  5.6   5.49  3.63
#>  5  1    Fair  G     SI1      63.1    59  4163  6.32  6.27  3.97
#>  6  2.01 Fair  E     SI2      62.1    66 14948  7.99  7.92  4.94
#>  7  0.7  Fair  G     VS1      56.2    65  2384  5.93  5.88  3.32
#>  8  0.7  Fair  I     VS1      60.2    66  2234  5.77  5.62  3.44
#>  9  0.7  Fair  G     VS2      66.5    57  2575  5.4   5.46  3.61
#> 10  1.13 Fair  F     VS1      64.5    55  7335  6.62  6.56  4.25
#> # … with 490 more rows
``````

``````diamonds %>%
group_by(cut) %>%
sample_n(size = 100) %>%
count(cut)
#> # A tibble: 5 x 2
#> # Groups:   cut [5]
#>   cut           n
#>   <ord>     <int>
#> 1 Fair        100
#> 2 Good        100
#> 3 Very Good   100