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.
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!
CodePudding user response:
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)
CodePudding user response:
Best to avoid using explicit loops whenever possible. Here's another way using base R:
set.seed(7)
iterations <- 5
sampsize <- 15
nrows <- nrow(mtcars)
samps <- rep(sample(1:nrows, sampsize, replace = FALSE), iterations)
random_rows <- matrix(samps, ncol = 15)
random_rows
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
[1,] 10 15 24 10 15 24 10 15 24 10 15 24 10 15 24
[2,] 19 26 27 19 26 27 19 26 27 19 26 27 19 26 27
[3,] 28 22 25 28 22 25 28 22 25 28 22 25 28 22 25
[4,] 7 8 12 7 8 12 7 8 12 7 8 12 7 8 12
[5,] 2 3 20 2 3 20 2 3 20 2 3 20 2 3 20