r - 在 R 函数中以不规则间隔对数据进行子集化
问题描述
我有这样的功能
extract = function(x)
{
a = x$2007[6:18]
b = x$2007[30:42]
c = x$2007[54:66]
}
子集需要以这种方式持续到 744。我需要跳过前 6 个数据点,然后每隔 12 个点提取一个新对象或列表。有没有更优雅的方法可以使用 for 循环或应用来做到这一点?
解决方案
旁注:如果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])
推荐阅读
- javascript - How To Generate Multiline Download File Javascript
- angular - 在没有实际运行函数角度测试的情况下运行函数
- sql-server - 使用 SQL Pivot 查询显示 13 个月的数据
- coq - 在同一个库中导出模块时出现 CoqIDE 错误
- java - 为什么netbeans没有在代码中显示系统输出
- c++ - C++ assembler conversion problems
- go - 即使我转到不存在的路由,net/http 也会呈现根路由
- grafana - 从 CPU 使用率中位数的子查询中选择前 10 名,并使用 Influx 显示时间序列数据
- python - Django 将普通查询集转换为迭代器
- scala - SBT 插件:传播编译器插件并在下游启用插件