作者ardodo (米虫)
看板R_Language
标题[问题] 取样的问题
时间Mon May 4 14:34:16 2015
版上先进大家好,我有个问题想请教大家
现在我手上有笔某大专院校22个系所的学生资料(共1万笔)
我想要在每个系所各取样30名学生资料出来分析,请问该怎麽做?
我想到的方法是:每个系所subset一次、随机抽30名出来存成一个物件,重覆22次
最後将上面22个物件rbind即可
但是这样的做法很费时也没有效率,想请问有没有比较快的方法?
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 163.14.191.172
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1430721259.A.0C8.html
1F:→ celestialgod: Assume dat is the dataset 05/04 16:03
2F:→ celestialgod: dat %>% split(.$department)%>%lapply(function(x) 05/04 16:07
3F:→ celestialgod: x[sample(1:nrow(x), 2),]) %>% rbindlist(.) 05/04 16:07
4F:→ celestialgod: department是dat中系所的变数 05/04 16:08
5F:→ celestialgod: base::split, data.table::rbindlist,magrittr::%>% 05/04 16:08
6F:→ celestialgod: 2是取样的样本数 05/04 16:09
7F:→ celestialgod: 你也可以用dplyr group_by做 05/04 16:10
8F:→ celestialgod: rbindlist(.) 可以用do.call(rbind, .)取代 05/04 16:10
9F:推 psinqoo: celestialgod 回文~这样看很花 05/04 16:59
10F:→ celestialgod: 不想要因此再开一篇文章QQ 05/04 18:01
11F:→ celestialgod: 才两行程式而已 05/04 18:01
12F:→ gsuper: 用 tapply() 和 sample() 找出大矩阵的 index 就好 05/13 11:33
13F:→ gsuper: tapply(1:10000,groupFactor,funciton(s){sample(s,30)}) 05/13 11:36
14F:→ celestialgod: 楼上,split可以接根据变数做切割,会方便很多 05/13 11:36
15F:→ gsuper: 然後: 大矩阵[index,] 05/13 11:36
16F:→ celestialgod: 其实会比tapply快。 05/13 11:36
17F:→ gsuper: Mm....split 也行 05/13 11:39
18F:→ gsuper: sapply(split(1:6,c(1,1,1,2,2,2)),sample,2) 这个感觉 05/13 11:41