简体   繁体   English

R中是否有一种简单的方法可以访问向量中负面元素的位置?

[英]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 ? 有没有一种简单的方法可以访问这些负面位置,即从前nm元素?

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): 使用tailhead (不同于副本):

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.

相关问题 一种计算向量中负元素数量的优雅方法? - An elegant way to count number of negative elements in a vector? 替换给定 R 中另一个向量的负数位置的列? - replace a column given the position of a negative number of another vector in R? 找到可能完全为正的 R 向量中第一个负数的位置 - Find the position of first negative number in a R vector that may be entirely positive Position 来自一个向量的元素在另一个向量中与 R - Position of elements from one vector in another vector with R 如何在 R 中明智地将元素添加到基于另一个向量 position 的向量中 - How to add elements to a vector based on another vector position wise in R 通过 position [R] 从另一个向量填充一个向量上的空元素 - Filling in empty elements on a vector from another vector by position [R] 在R中向量中找到从正到负切换的最快方法 - Fastest way to find switching from positive to negative in a vector in R 是否有一种简单的方法可以对 R 中的向量中的元素执行算术运算? - Is there an easy way of performing arithmetic on elements in a vector in R? 有没有办法在R中的命名向量中选择一系列元素? - Is there a way to select a range of elements in a named vector in R? 有没有办法矢量化访问矢量的多个元素的操作? - Is there a way to vectorize operations that access multiple elements of a vector?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM