【问题标题】:Repeat vector when its length is not a multiple of desired total length当其长度不是所需总长度的倍数时重复向量
【发布时间】:2012-08-03 11:52:41
【问题描述】:

我有一个包含 1666 行的数据框。我想添加一个重复序列为1:5 的列,以与cut() 一起使用来进行交叉验证。它看起来像这样:

   Y      x1       x2       Id1
   1      .15      3.6       1
   0      1.1      2.2       2
   0      .05      3.3       3
   0      .45      2.8       4
   1      .85      3.1       5
   1      1.01     2.9       1
  ...      ...     ...      ...

我尝试了以下 2 种方法,但收到一条错误消息,因为它似乎只在完整的 seq() 参数的增量中添加数字:

>   tr2$Id1 <- rep(seq(1,5,1), (nrow(tr2)/5))
Error in `$<-.data.frame`(`*tmp*`, "Id", value = c(1, 2, 3, 4, 5, 1, 2,  : 
  replacement has 1665 rows, data has 1666
>   tr2$Id1 <- rep(seq(1,5,1), (nrow(tr2)/5) + (nrow(tr2)%%5))
Error in `$<-.data.frame`(`*tmp*`, "Id", value = c(1, 2, 3, 4, 5, 1, 2,  : 
  replacement has 1670 rows, data has 1666

有什么建议吗?

【问题讨论】:

    标签: r seq rep


    【解决方案1】:

    使用rep()rep_lenlength.out 参数(rep 的“更快的简化版本”):

    length.out:非负整数。输出向量的期望长度

    这是一个使用内置数据集汽车的示例。

    str(cars)
    'data.frame':   50 obs. of  2 variables:
     $ speed: num  4 4 7 7 8 9 10 10 10 11 ...
     $ dist : num  2 10 4 22 16 10 18 26 34 17 ...
    

    添加分组列:

    cars$group <- rep(1:3, length.out = 50L)
    

    检查结果:

    head(cars)
      speed dist group
    1     4    2     1
    2     4   10     2
    3     7    4     3
    4     7   22     1
    5     8   16     2
    6     9   10     3
    
    tail(cars)
       speed dist group
    45    23   54     3
    46    24   70     1
    47    24   92     2
    48    24   93     3
    49    24  120     1
    50    25   85     2
    

    【讨论】:

      【解决方案2】:

      像这样的东西?

      df <- data.frame(rnorm(1666))
      df$cutter <- rep(1:5, length.out=1666)
      
      tail(df)
           rnorm.1666. cutter
      1661  0.11693169      1
      1662 -1.12508091      2
      1663  0.25441847      3
      1664 -0.06045037      4
      1665 -0.17242921      5
      1666 -0.85366242      1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-15
        • 1970-01-01
        • 1970-01-01
        • 2020-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多