【问题标题】:R repeat n times [duplicate]R重复n次[重复]
【发布时间】:2017-01-23 01:10:40
【问题描述】:

我有一个应用程序需要将 n 个对象分类到 x 个连续编号的组中。当 n 对象可以使用 rep() 函数在 x 组中平均分配时,这很简单:

objects <- c(1: 10)
groups <- 5
assign1 <- rep(1:groups, times= (length(objects)/groups))
assign1
[1] 1 2 3 4 5 1 2 3 4 5

但是,当对象不能按组大小整除时,组分配可能太长或太短:

groups <- 7
assign2 <- rep(1:groups, times= (length(objects)/groups))
assign2
[1] 1 2 3 4 5 6 7

这可以通过以下方式解决:

assign_set <- rep(1:groups, times= (length(objects)/groups)+1 )
assign3 <- assign_set[1:length(objects)]
assign3
[1] 1 2 3 4 5 6 7 1 2 3

这个解决方案似乎效率低下。有没有更有效的方法来完成这项任务?

【问题讨论】:

    标签: r


    【解决方案1】:

    这个rep_len 可能就是你要找的东西

    rep_len(1:7, length.out = length(objects))
    # [1] 1 2 3 4 5 6 7 1 2 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      • 2012-05-06
      相关资源
      最近更新 更多