首页 > 解决方案 > 在 R 函数中以不规则间隔对数据进行子集化

问题描述

我有这样的功能

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

子集需要以这种方式持续到 744。我需要跳过前 6 个数据点,然后每隔 12 个点提取一个新对象或列表。有没有更优雅的方法可以使用 for 循环或应用来做到这一点?

标签: rfunctionfor-loopsubsetapply

解决方案


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

要生成该整数序列,让我们尝试

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])

推荐阅读