Chuck Davidson
Chuck Davidson

Reputation: 31

Reverse a vector without rev()

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.

Upvotes: 1

Views: 709

Answers (3)

NicChr
NicChr

Reputation: 1253

I would simply use v[length(v):0]

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 102529

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

Upvotes: 1

jay.sf
jay.sf

Reputation: 73572

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)

Upvotes: 0

Related Questions