在R函数中以不规则的间隔替换数据

问题描述 投票:0回答:1

我有这样的功能

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个回答
0
投票

旁注:如果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])
© www.soinside.com 2019 - 2024. All rights reserved.