如何反转向量? [英] How to reverse order a vector?
问题描述
假设我有一个向量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)
时,它返回NA,而用户通常期望不进行任何排序将不返回任何内容,不进行任何排序将返回不可用的内容-这确实使它变得很大我的情况有所不同.
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.
这篇关于如何反转向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!