fork download
  1. dt <-
  2. data.frame(
  3. id = 182,
  4. group = c(rep("A", 20), rep("B", 32), rep("C", 50), rep("D", 80)),
  5. y = rnorm(182)
  6. )
  7.  
  8. # 採用 aggregate
  9. set.seed(1234)
  10. aggregate(dt$y, list(dt$group), function(x){
  11. N <- length(x)
  12. n <- c(15, 20, 25, 35)[which(c(20, 32, 50, 80) %in% N)] # 判斷要抽幾個
  13. ind <- sample(1:N, n)
  14. mean(x[ind])
  15. })
  16. # Group.1 x
  17. # 1 A -0.2242983
  18. # 2 B 0.3519958
  19. # 3 C 0.1363614
  20. # 4 D 0.4146774
  21.  
  22. # 採用 tapply
  23. set.seed(1234)
  24. tapply(dt$y, dt$group, function(x){
  25. N <- length(x)
  26. n <- c(15, 20, 25, 35)[which(c(20, 32, 50, 80) %in% N)] # 判斷要抽幾個
  27. mean(x[sample(1:N, n)])
  28. })
  29. # A B C D
  30. # -0.2242983 0.3519958 0.1363614 0.4146774
  31.  
Success #stdin #stdout 0.19s 184320KB
stdin
Standard input is empty
stdout
  Group.1           x
1       A  0.19679127
2       B  0.38061224
3       C  0.10668370
4       D -0.02751585
          A           B           C           D 
 0.19679127  0.38061224  0.10668370 -0.02751585