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

dplyr, purrr or similar process to replace for loop in R

I have a distribution of groups with a given number of individuals; for example: {2, 4, 1, 1, 2, 3}, where Group 1 has 2 individuals, Group 2 has 4 individuals, Group 3 has 1, Group 4 has 1, etc. I want to build a table where there is a unique row for each Group/Individual combination. (Desired table format at the bottom of the question).

I currently use a for loop:

num.groups <- 10
mu <- 4
sd <- 1

group.dist <- round(rnorm(num.groups, mean = mu, sd = sd))

xx <- NULL
for (i in 1:length(group.dist)) {
  temp <- data.frame(Group = i, Individual = 1:group.dist[i])
  xx <- rbind(xx, temp)
}

I’m trying to get away from using for loops in general, and the actual version of my code has hundreds of groups and I will be running a simulation thousands of times, so I’m hoping there is a more efficient method of doing this.

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 apologize if someone has already asked this question, it is a difficult specific situation to google. Thanks!

The table would look like this:
enter image description here

>Solution :

For example:

library(tidyverse)
d <- tibble(Group = seq_along(group.dist), n = group.dist)

uncount(d, n, .id = 'Individual')
# A tibble: 45 × 2
# Groups:   Group [10]
   Group Individual
   <int>      <int>
 1     1          1
 2     1          2
 3     1          3
 4     1          4
 5     2          1
 6     2          2
 7     2          3
 8     2          4
 9     3          1
10     3          2
# … with 35 more rows
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