R 中 rep(`each=`) 的矢量化替代方案

A vectorized alternative to rep(`each=`) in R

我在 rep() 中收到一条警告消息,指出 each= 参数未矢量化。

tidyverse() 或其他基础 R 替代方案中是否有 rep() 的矢量化替代方案?

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

我不清楚你是否真的想要 repeachtimes 版本。要使用 each 版本,可以在 sapply:

中使用 rep
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

使用 times 参数,而不是 each 参数:

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

reprex package (v2.0.0)

于 2021-10-25 创建