Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 17945

How to distribute n cases by row in a group in a data frame from another dataframe

$
0
0

I have one dataframe with the amount of cases I want to add to the rows of a data frame. This is the data frame with the cases to distribute:

groups <- data.frame(Id = 1:5, Cases_num = c(6, 3, 8, 20, 10))

This is the data frame with all cases:

dat <- data.frame(Id = c(rep(1,8), rep(2,6), rep(3,10), rep(4,60), rep(5,15)),                  g  = c(rep(1,4), rep(2,4), rep(1,3), rep(2,3), rep(1,5),                          rep(2,5), rep(1,15), rep(2,15), rep(3,15), rep(4,15),                          rep(1,5), rep(2,5), rep(3,5)),                  f  = c(rep(1,8), rep(2,6), rep(3,10), rep(1,60), rep(2,15)))

I am using a for loop to try to distribute one by one in each row by group (First group):

a <- subset(dat, Id == 1)n <- nrow(a)for (i in 1:length(a)) {  while (i <= n) {    a[i] <- a[i] + 1    i <- i + 1    n <- n -i  }  print(a)}

This is the result:

[1] 2 2 1 1 1 1 1 1[1] 2 2 1 1 1 1 1 1[1] 2 2 1 1 1 1 1 1[1] 2 2 1 1 1 1 1 1[1] 2 2 1 1 1 1 1 1[1] 2 2 1 1 1 1 1 1[1] 2 2 1 1 1 1 1 1[1] 2 2 1 1 1 1 1 1

How can I adjust the loop to get this result?

[1] 2 2 2 2 2 2 1 1

Is there a way to do it for all groups at once?


Viewing all articles
Browse latest Browse all 17945

Trending Articles