根据组随机抽取 [英] Take randomly sample based on groups

查看:69
本文介绍了根据组随机抽取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由将近50,000行组成的df,分布在15个不同的ID中(每个ID都有数千个观测值)。 df看起来像:

I have a df made by almost 50,000 rows spread in 15 different IDs (every ID has thousands of observations). df looks like:

        ID  Year    Temp    ph
1       P1  1996    11.3    6.80
2       P1  1996    9.7     6.90
3       P1  1997    9.8     7.10
...
2000    P2  1997    10.5    6.90
2001    P2  1997    9.9     7.00
2002    P2  1997    10.0    6.93

我想为每个ID取500个随机行(因此P1为500,P2为500,....)并创建一个新df。我尝试:

I want to take 500 random rows for every ID (so 500 for P1, 500 for P2,....) and create a new df. I try:

new_df<-df[df$ID %in% sample(unique(dfID),500),]

但是它随机需要一个ID,而每个ID需要500个随机行。

But it takes randomly one ID, while I need 500 random rows for every ID.

推荐答案

尝试一下:

library(plyr)
ddply(df,.(ID),function(x) x[sample(nrow(x),500),])

这篇关于根据组随机抽取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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