子集矢量:如何安全地以编程方式传递负指数? [英] Subsetting vector: how to programatically pass negative index safely?
问题描述
给定一个向量,比如 v = 1:10
,可以使用否定索引从 v
中删除元素,例如 v [-1]
, v [-length(v)]
, v [ - c(2,3)]
,分别删除第一个,最后一个和第二个/第三个元素。
Given a vector, say v = 1:10
, one can remove elements from v
using negative indexing, e.g. v[-1]
, v[-length(v)]
, v[-c(2,3)]
, to remove the first, last and 2nd/3rd element respectively.
我想拆分 v
传入拆分索引 n
,取值0到 length(v)
。以下代码:
I would like to split v
by passing in a split index n
, taking values 0 to length(v)
. The code below:
v1 <- v[1:n]
v2 <- v[-c(1:n)]
完全正常,但 n = 0
。现在我知道 1:n
通常是不安全的,应该用 seq_len(n)
替换,但是,分配 v2< - v [-seq_len(0)]
生成一个空向量。
works perfectly fine except for n = 0
. Now I know that 1:n
is generally unsafe and should be replaced with seq_len(n)
, however, the assignment v2 <- v[-seq_len(0)]
produces an empty vector.
有没有办法做这个'安全'使用括号子集符号?否则我知道如何使用头部和尾部来做:
Is there way of doing this 'safely' using the bracket subsetting notation? Otherwise I know how to do it using head and tails:
v1 <- head(v, n)
v2 <- tail(v, length(v) - n)
相关的其他q / as:
Relevant other q/as:
推荐答案
如果,您可以使用
()
括号内的语句。例如,如果 n
为零,则只返回整个向量,否则删除序列 1:n
。 / p>
You could use an if()
statement inside the brackets. For example, this will just return the whole vector if n
is zero and remove the sequence 1:n
otherwise.
x <- 1:10
n <- 0
x[ if(n == 0) TRUE else -seq_len(n) ] ## n == 0 is !n for the golfers
# [1] 1 2 3 4 5 6 7 8 9 10
n <- 5
x[ if(n == 0) TRUE else -seq_len(n) ]
# [1] 6 7 8 9 10
这篇关于子集矢量:如何安全地以编程方式传递负指数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!