从数据表中,每组随机选择一行 [英] from data table, randomly select one row per group

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

问题描述

我正在寻找一种从数据表中选择行的有效方法,以便我为特定列中的每个唯一值都有一个代表行.

I'm looking for an efficient way to select rows from a data table such that I have one representative row for each unique value in a particular column.

让我举一个简单的例子:

Let me propose a simple example:

require(data.table)

y = c('a','b','c','d','e','f','g','h')
x = sample(2:10,8,replace = TRUE)
z = rep(y,x)
dt = as.data.table( z )

我的目标是通过对 z 列中的每个字母 a-h 采样一行来对数据表 dt 进行子集化.

my objective is to subset data table dt by sampling one row for each letter a-h in column z.

推荐答案

OP 在示例中仅提供了一个列.假设原始数据集中有多列,我们按'z'分组,sample每组行序列中的1行,得到行索引(.I),提取具有行索引 ($V1) 的列,并使用它对 'dt' 的行进行子集化.

OP provided only a single column in the example. Assuming that there are multiple columns in the original dataset, we group by 'z', sample 1 row from the sequence of rows per group, get the row index (.I), extract the column with the row index ($V1) and use that to subset the rows of 'dt'.

dt[dt[ , .I[sample(.N,1)] , by = z]$V1]

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

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