Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

from data table, randomly select one row per group

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 )

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

like image 910
Kerry Avatar asked Nov 24 '15 06:11

Kerry


2 Answers

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]
like image 60
akrun Avatar answered Nov 13 '22 11:11

akrun


You can use dplyr

library(dplyr)

dt %>%
  group_by(z) %%
  sample_n(1)
like image 6
bramtayl Avatar answered Nov 13 '22 11:11

bramtayl