[英]Is there a simple way in R to access negative elements' position in a vector?
say I have the following vector: 说我有以下矢量:
v = c(1:8)
and I would like to access the elements 7,8,1,2,3 in that order. 我想按顺序访问元素7,8,1,2,3。 That is, something like
就是这样的
v[-2:3]
would be great. 会很好。 Is there a simple way to access these negative positions, ie, elements from
n
before last to m
? 有没有一种简单的方法可以访问这些负面位置,即从前
n
到m
元素?
You could use the modulus operator (ie, the remainder): 您可以使用模数运算符(即余数):
v[-2:3 %% (length(v)+1)]
Output: 输出:
[1] 7 8 1 2 3
Using tail
and head
(different then the duplicate one): 使用
tail
和head
(不同于副本):
c(tail(v,2),head(v,3))
OR we can use union
to combine the answer: 或者我们可以使用
union
来结合答案:
union(tail(v,2),head(v,3))
Output: 输出:
[1] 7 8 1 2 3
以下是使用负元素位置的两个其他选项: c(v[-6:-1], v[1:3])
或c(v[-c(1:6)], v[1:3])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.