【问题标题】:A vectorized alternative to rep(`each=`) in RR 中 rep(`each=`) 的矢量化替代方案
【发布时间】:2021-12-11 02:45:48
【问题描述】:

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

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

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

【问题讨论】:

  • 预期输出是什么?

标签: r function loops vectorization mapply


【解决方案1】:

使用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 日创建

【讨论】:

    【解决方案2】:

    我不清楚您是否真的想要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
    

    【讨论】:

      猜你喜欢
      • 2016-09-28
      • 1970-01-01
      • 2021-08-09
      • 2021-03-23
      • 1970-01-01
      • 2015-08-28
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多