Re: [R] Randomly select one row by group from a matrix

2017-05-18 Thread David L Carlson
From: R-help [mailto:r-help-boun...@r-project.org] On Behalf Of Bert Gunter Sent: Thursday, May 18, 2017 12:39 PM To: Ulrik Stervbo Cc: r-help@r-project.org; Marine Regis Subject: Re: [R] Randomly select one row by group from a matrix If I understand corrrectly, this is easily accomplishe

Re: [R] Randomly select one row by group from a matrix

2017-05-18 Thread Bert Gunter
If I understand corrrectly, this is easily accomplished in base R via ?tapply and indexing. e.g. set.seed(1234) ## for reproducibility grp <- sample.int(5,size = 30,rep = TRUE) ## a grouping vector ## Could be just a column of your matrix or frame indx <- tapply(seq_along(grp),grp, sample,size =

Re: [R] Randomly select one row by group from a matrix

2017-05-18 Thread Ulrik Stervbo
Hi Marine, your manipulation of the matrix is quite convoluted, and it helps to expand a bit: test_lst <- split(test, test[,c("id")]) test_lst$`1` after splitting, your matrix has gone back to be a plain vector, which makes the sampling fail. The reason is that, a matrix - behind the scenes - i