[英]Reverse a vector without rev()
We have to reverse it without rev().我们必须在没有 rev() 的情况下反转它。 Not allowed to use if/for loops.
不允许使用 if/for 循环。 It has to work for numeric(0) as well.
它也必须适用于 numeric(0)。
v[length(v):1]
Does not output correctly for vectors with length 0.对于长度为 0 的向量,output 不正确。
Just use a switch
, and it requires only a single calculation of the length.只需使用
switch
,只需计算一次长度。
v <- numeric(0L) ## creating vector of length zero
v[{len <- length(v); switch((len > 0L) + 1L, 0L, len:1)}]
# numeric(0)
Try this尝试这个
> v <- numeric(0)
> v[length(v) - seq_along(v) + 1]
numeric(0)
and和
> v <- c(5, 2, 7, 8, 3)
> v[length(v) - seq_along(v) + 1]
[1] 3 8 7 2 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.