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

Marine Regis marine.regis at hotmail.fr
Thu May 18 17:18:34 CEST 2017


Hello,
I would like to randomly select one row by group from a matrix. Here is an example where there is one row by group. The code gives an error message:
test <- matrix(c(4,4, 6,2, 1,2), nrow = 2, ncol = 3, dimnames = list(NULL, c("xcor", "ycor", "id")))
do.call(rbind, lapply(split(test, test[,c("id")]), function(x) x[sample(nrow(x), 1), ]))
 Show Traceback

 Rerun with Debug

Error in sample.int(length(x), size, replace, prob) :
  invalid first argument


How can I modify the code so that it works when there are several rows or one row for a given group?
Thanks very much for your time
Have a nice day
Marine


	[[alternative HTML version deleted]]



More information about the R-help mailing list