【问题标题】:Subsetting data at an irregular interval in an R function在 R 函数中以不规则间隔对数据进行子集化
【发布时间】:2020-10-07 14:22:52
【问题描述】:

我有这样的功能

extract = function(x)
{
a = x$2007[6:18]
b = x$2007[30:42]
c = x$2007[54:66]
}

子集需要以这种方式一直持续到 744。我需要跳过前 6 个数据点,然后每隔 12 个点将其拉出到一个新对象或列表中。有没有更优雅的方法可以使用 for 循环或应用来执行此操作?

【问题讨论】:

    标签: r function for-loop subset apply


    【解决方案1】:

    旁注:如果2007 确实是一个列名(您必须明确地这样做,R 默认将数字转换为以字母开头的名称,请参阅make.names("2007")),那么x$"2007"[6:18](等)应该为列参考工作。

    要生成这个整数序列,我们试试

    nr <- 100
    ind <- seq(6, nr, by = 12)
    ind
    # [1]  6 18 30 42 54 66 78 90
    ind[ seq_along(ind) %% 2 == 1 ]
    # [1]  6 30 54 78
    ind[ seq_along(ind) %% 2 == 0 ]
    # [1] 18 42 66 90
    Map(seq, ind[ seq_along(ind) %% 2 == 1 ], ind[ seq_along(ind) %% 2 == 0 ])
    # [[1]]
    #  [1]  6  7  8  9 10 11 12 13 14 15 16 17 18
    # [[2]]
    #  [1] 30 31 32 33 34 35 36 37 38 39 40 41 42
    # [[3]]
    #  [1] 54 55 56 57 58 59 60 61 62 63 64 65 66
    # [[4]]
    #  [1] 78 79 80 81 82 83 84 85 86 87 88 89 90
    

    所以你可以在你的函数中使用它来创建一个子集列表:

    nr <- nrow(x)
    ind <- seq(6, nr, by = 12)
    out <- lapply(Map(seq, ind[ seq_along(ind) %% 2 == 1 ], ind[ seq_along(ind) %% 2 == 0 ]),
                  function(i) x$"2007"[i])
    

    【讨论】:

    • 列名实际上是jan2007_tempK,我只是想简洁,哎呀!非常感谢
    【解决方案2】:

    我们可以使用

    split( x[7:744] , cut(7:744,seq(7,744,12)) )
    

    【讨论】:

      猜你喜欢
      • 2015-04-13
      • 2019-09-26
      • 2021-09-16
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      相关资源
      最近更新 更多