从数据框中按类别选择随机行? [英] Selecting random rows by category from a data frame?

查看:214
本文介绍了从数据框中按类别选择随机行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框如下:

类别名称值

如何选择每个类别5个随机名称?使用样本返回随机行使用所有行作为可能的候选。但是,我想指定每个类别的随机行数。任何建议?

How would I select say, 5 random names per category? Using sample returns random rows using all rows as possible candidates. However, I want to specify the number of random rows per category. Any suggestions?

更新:我可以使用 ddply

推荐答案

在没有测试用例的情况下,最好的猜测:

Best guess in absence of test cases:

  do.call( rbind, lapply( split(dfrm, df$cat) ,
                         function(df) df[sample(nrow(df), 5) , ] )
          )



Tested with Jonathan's data:

> do.call( rbind, lapply( split(df, df$Category) ,
+                          function(df) df[sample(nrow(df), 5) , ] )
+           )

      Category Name      Value   
1.8          1    8 -0.2496109   #  useful side-effect of labeling source group
1.15         1   15 -0.4037368
1.17         1   17 -0.4223724
1.12         1   12 -0.9359026
1.18         1   18  0.3741184
2.37         2   37  0.3033610
2.34         2   34 -0.4517738
2.36         2   36 -0.7695923
snipped remainder

这篇关于从数据框中按类别选择随机行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆