问题描述
假设我有一个向量 v
,我如何得到它的反向,即最后一个元素?
Suppose I have a vector v
, how do I get its reverse, i.e. last element first?
首先想到的是v[length(v):1]
,但是当v
是numeric(0),虽然用户通常希望排序不返回任何内容,但不排序返回不可用的内容 - 这对我来说确实有很大的不同.
The first thing that comes to me is
v[length(v):1]
, but it returns NA when v
is numeric(0)
, while user normally expect sorting nothing returns nothing, not sorting nothing returns the unavailable thing - it does make a big difference in my case.
推荐答案
你就快到了;
rev
满足您的需求:
You are almost there;
rev
does what you need:
rev(1:3)
# [1] 3 2 1
rev(numeric(0))
# numeric(0)
原因如下:
rev.default
# function (x)
# if (length(x)) x[length(x):1L] else x
# <bytecode: 0x0b5c6184>
# <environment: namespace:base>
在
numeric(0)
的情况下,length(x)
返回0.由于if
需要一个逻辑条件,它强制length(x)
到 TRUE
或 FALSE
.当 x
为 0 并且 TRUE
为任何其他数字时,as.logical(x)
恰好是 FALSE
.
In the case of
numeric(0)
, length(x)
returns 0. As if
requires a logical condition, it coerces length(x)
to TRUE
or FALSE
. It happens that as.logical(x)
is FALSE
when x
is 0 and TRUE
for any other number.
因此,
if (length(x))
可以精确地测试您想要的内容 - x
的长度是否为零.如果不是,length(x):1L
有一个理想的效果,否则就不需要反转任何东西,正如@floder 在评论中所解释的那样.
Thus,
if (length(x))
tests precisely what you want - whether x
is of length zero. If it isn't, length(x):1L
has a desirable effect, and otherwise there is no need to reverse anything, as @floder has explained in the comment.
这篇关于如何倒序向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!