rnorouzian
rnorouzian

Reputation: 7517

Double looping to get a dataframe in R (tidyverse)

I want to repeat sample(1:11, 1) 6 times at 5 different rounds. In the final output, I want a data.frame where each round is a row (see below).

Is this achievable in tidyverse (e.g., purrr::map_df) or BASE R?

round1 4 5 6 7 8 9
round2 3 2 1 4 4 1
round3 5 4 2 2 1 1
round4 7 7 7 7 7 1
round5 1 8 8 8 8 1

Upvotes: 0

Views: 56

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 389045

We can use replicate

t(replicate(5, sample(1:11, 6, replace = TRUE)))

As @thelatemail mentioned we can sample only once and put the data in a matrix.

nr <- 5
nc <- 6
matrix(sample(1:11, nr * nc, replace = TRUE), nr, nc)

Upvotes: 2

andrew_reece
andrew_reece

Reputation: 21274

As OP asked about purrr, here's a tidyverse solution which gets the row names specified in the expected output:

library(tidyverse)

rounds <- paste0("round", 1:5) 

rounds %>% 
  setNames(rounds) %>% 
  map_dfc(~sample(1:11, 6, replace = TRUE)) %>% 
  t()

       [,1] [,2] [,3] [,4] [,5] [,6]
round1    1   11   10    6    5   10
round2    9    2    3    3    2   10
round3    8    8    2   11    6    7
round4    1    7    8    6   11   10
round5    1    7    7    3    1    8

Upvotes: 0

Abdessabour Mtk
Abdessabour Mtk

Reputation: 3888

why not use lapply to sample 6 elements 5 times. the replace flag in sample gives the chance of pulling the same number more than one time.

 data.frame(do.call(rbind, lapply(1:5,function(x) sample(1:11, 6, replace=T)))

Upvotes: 0

Related Questions