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

Issue of generating conditional numbers to a set frequency in R

I am having a issue generating conditional numbers. Repeated frequency of the number is shown in "size". For example, 1 should be repeated 3 times and 2 should be repeated 2 times and so on.
My desired output is shown below but I am unable to achieve this. Can somebody correct me please?

Desired output 

   x1
1   1
2   1
3   1
4   2
5   2
6   3
7   4
8   4
9   5
10  5

data <- data.frame(x1= rep(c(1),each=10))
data    

size <- as.array(c(3,2,1,2,2))

for(i in 1:5) {                          
  x_val <- size[i]
  new <- rep(c(x_val), each=x_val)      
  data[nrow(size[i]) + 1, ] <- new      
}
print(data)


   x1
1   1
2   1
3   1
4   1
5   1
6   1
7   1
8   1
9   1
10  1

>Solution :

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

We could use rep with times

data.frame(x1 = rep(seq_along(size), size))

-output

  x1
1   1
2   1
3   1
4   2
5   2
6   3
7   4
8   4
9   5
10  5

If we need a for loop

x1 <- c()
for(i in seq_along(size)) x1 <- c(x1, rep(i, each = size[i]))
x1
#[1] 1 1 1 2 2 3 4 4 5 5
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