Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: Sampling a random row from each data frame in a list of data frames

I seem to be having trouble trying to sample a random row from each data frame in my list of data frames.

Here is the code for reproducing the list:

output <- list()

iterations <- 5
for(i in 1:iterations){
  output[[i]] <-  mtcars <- mtcars[sample(nrow(mtcars), size = 15, replace = FALSE), ]

}

After getting the list of data frames, my goal is to take a random row from each of the data frames then add the sampled rows to a numbered list each as data frames.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think that I may have to use the "map" function but I am not sure how to go about doing this.

Any help at all would be greatly appreciated!

>Solution :

You can do this lots of ways, I like the map_dfr function from the purrr package which returns a nice data frame.

library(purrr)

# add a rownumber so we can see we are drawing different rows
mtcars$rownumber <- 1:nrow(mtcars)

# quick list of rows
dflist <- list(mtcars, mtcars, mtcars)

# purrr map solution
map_dfr(dflist, .f = function(df){df[sample(nrow(df),1),]})
#>              mpg cyl  disp  hp drat    wt qsec vs am gear carb rownumber
#> Merc 450SL  17.3   8 275.8 180 3.07 3.730 17.6  0  0    3    3        13
#> Volvo 142E  21.4   4 121.0 109 4.11 2.780 18.6  1  1    4    2        32
#> AMC Javelin 15.2   8 304.0 150 3.15 3.435 17.3  0  0    3    2        23

Created on 2022-02-23 by the reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading