We have to reverse it without rev(). Not allowed to use if/for loops. It has to work for numeric(0) as well.
v[length(v):1]
Does not output correctly for vectors with length 0.
CodePudding user response:
Just use a switch
, and it requires only a single calculation of the length.
v <- numeric(0L) ## creating vector of length zero
v[{len <- length(v); switch((len > 0L) 1L, 0L, len:1)}]
# numeric(0)
CodePudding user response:
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