I get a warning message in rep() that says each= argument is not vectorized.
Is there a vectorized alternative to rep() perhaps in tidyverse() or other base R alternative?
n_study <- 5
n_per_study_rows <- c(3,5,3,3,2)
rep(1:n_study, each=n_per_study_rows)
Warning message: first element used of 'each' argument
CodePudding user response:
Use the times argument, not the each argument:
n_study <- 5
n_per_study_rows <- c(3,5,3,3,2)
rep(1:n_study, times=n_per_study_rows)
#> [1] 1 1 1 2 2 2 2 2 3 3 3 4 4 4 5 5
Created on 2021-10-25 by the reprex package (v2.0.0)
CodePudding user response:
It's not clear to me from the question whether you actually wanted the each or times version of rep. To use the each version, you can use rep inside sapply:
unlist(sapply(n_per_study_rows, function(x) rep(1:n_study, each = x)))
#> [1] 1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 1 1
#> [35] 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4 1 1 2 2 3 3 4 4
