在 R 中传递空索引
Passing empty index in R
假设我想对一个向量进行子集化 a
,我可以将索引的值传递给变量中的子集,例如a[idx]
.
我应该设置什么值 idx
以获得相当于获得整个 a
(即 a[]
)的值?
基本上我有一个以 idx
作为参数的函数,并且想传递一个值来处理整个数据集。我假设应该有比 1:length(a)
.
更好的东西
您可以使用一个小技巧:将 idx
设置为 TRUE
a[TRUE]
@ahmohamed 的回答是正确的,并且是一种非常简洁的解决问题的方法。以防万一您正在处理大型数据集,让我来说明回收逻辑向量和使用数字索引的性能差异:
a <- sample(1e6, 1e7, TRUE)
library(microbenchmark)
microbenchmark(a[TRUE], a[seq_along(a)])
#Unit: milliseconds
# expr min lq median uq max neval
# a[TRUE] 238.10089 254.63311 261.03451 287.7352 1163.8499 100
# a[seq_along(a)] 64.49373 95.48278 98.00964 142.4811 709.2872 100
子集化中的索引参数允许为"missing"(参见?"["
):
ff1 = function(x, i) x[i]
ff2 = function(x, i = TRUE) x[i]
ff3 = function(x, i = seq_along(x)) x[i]
ff4 = function(x, i = substitute()) x[i]
a = sample(10)
a
# [1] 3 8 2 6 9 7 5 1 4 10
ff1(a)
# [1] 3 8 2 6 9 7 5 1 4 10
ff2(a)
# [1] 3 8 2 6 9 7 5 1 4 10
ff3(a)
# [1] 3 8 2 6 9 7 5 1 4 10
ff4(a)
# [1] 3 8 2 6 9 7 5 1 4 10
a = runif(1e6)
identical(ff1(a), ff2(a))
#[1] TRUE
identical(ff1(a), ff3(a))
#[1] TRUE
identical(ff1(a), ff4(a))
#[1] TRUE
microbenchmark::microbenchmark(ff1(a), ff2(a), ff3(a), ff4(a), times = 25)
#Unit: milliseconds
# expr min lq median uq max neval
# ff1(a) 2.026772 2.131173 2.207037 2.930885 3.789409 25
# ff2(a) 12.091727 12.151931 12.318625 12.740057 16.829445 25
# ff3(a) 8.930464 9.104118 9.454557 9.643175 13.131213 25
# ff4(a) 2.024684 2.090108 2.156577 2.289166 3.496391 25
假设我想对一个向量进行子集化 a
,我可以将索引的值传递给变量中的子集,例如a[idx]
.
我应该设置什么值 idx
以获得相当于获得整个 a
(即 a[]
)的值?
基本上我有一个以 idx
作为参数的函数,并且想传递一个值来处理整个数据集。我假设应该有比 1:length(a)
.
您可以使用一个小技巧:将 idx
设置为 TRUE
a[TRUE]
@ahmohamed 的回答是正确的,并且是一种非常简洁的解决问题的方法。以防万一您正在处理大型数据集,让我来说明回收逻辑向量和使用数字索引的性能差异:
a <- sample(1e6, 1e7, TRUE)
library(microbenchmark)
microbenchmark(a[TRUE], a[seq_along(a)])
#Unit: milliseconds
# expr min lq median uq max neval
# a[TRUE] 238.10089 254.63311 261.03451 287.7352 1163.8499 100
# a[seq_along(a)] 64.49373 95.48278 98.00964 142.4811 709.2872 100
子集化中的索引参数允许为"missing"(参见?"["
):
ff1 = function(x, i) x[i]
ff2 = function(x, i = TRUE) x[i]
ff3 = function(x, i = seq_along(x)) x[i]
ff4 = function(x, i = substitute()) x[i]
a = sample(10)
a
# [1] 3 8 2 6 9 7 5 1 4 10
ff1(a)
# [1] 3 8 2 6 9 7 5 1 4 10
ff2(a)
# [1] 3 8 2 6 9 7 5 1 4 10
ff3(a)
# [1] 3 8 2 6 9 7 5 1 4 10
ff4(a)
# [1] 3 8 2 6 9 7 5 1 4 10
a = runif(1e6)
identical(ff1(a), ff2(a))
#[1] TRUE
identical(ff1(a), ff3(a))
#[1] TRUE
identical(ff1(a), ff4(a))
#[1] TRUE
microbenchmark::microbenchmark(ff1(a), ff2(a), ff3(a), ff4(a), times = 25)
#Unit: milliseconds
# expr min lq median uq max neval
# ff1(a) 2.026772 2.131173 2.207037 2.930885 3.789409 25
# ff2(a) 12.091727 12.151931 12.318625 12.740057 16.829445 25
# ff3(a) 8.930464 9.104118 9.454557 9.643175 13.131213 25
# ff4(a) 2.024684 2.090108 2.156577 2.289166 3.496391 25