在 R 中传递空索引 [英] Passing empty index in R
本文介绍了在 R 中传递空索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我想对向量 a
进行子集化,我可以将索引的值传递给变量中的子集,例如a[idx]
.
Say I want to subset a vector a
, I can pass the value of the indices to subset in a variable e.g. a[idx]
.
我应该设置什么值 idx
以获得等效于获取整个 a
(即 a[]
)?
What value should I set idx
to get the equivalent of getting the whole a
( i.e. a[]
) ?
基本上我有一个以 idx
作为参数的函数,并且想传递一个值来处理整个数据集.我假设应该有比 1:length(a)
更好的东西.
Basically I have a function with idx
as the argument, and would like to pass a value to process the whole dataset. I'm assuming there should be something better than 1:length(a)
.
推荐答案
子集的索引参数允许缺失"(见?"["
):
The index argument in subsetting is allowed to be "missing" (see ?"["
):
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
这篇关于在 R 中传递空索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文