Akira
Akira

Reputation: 2870

How to reverse a list in R?

I'm trying to reverse a list with function list.reverse. I run an example from its documentation.

x <- list(a=1,b=2,c=3)
list.reverse(x)

R returns an error message "Error in list.reverse(x) : could not find function "list.reverse" ".

Upvotes: 5

Views: 5712

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

The function does work. You have not loaded or installed rlist.

Try :

rlist::list.reverse(x)

#$c
#[1] 3

#$b
#[1] 2

#$a
#[1] 1

and so does base R rev works :

rev(x)

#$c
#[1] 3

#$b
#[1] 2

#$a
#[1] 1

Upvotes: 9

Duck
Duck

Reputation: 39595

Try this base R solution:

#Data
x <- list(a=1,b=2,c=3)
#Reverse
x[rev(1:length(x))]

Output:

$c
[1] 3

$b
[1] 2

$a
[1] 1

And using the function you mentioned, first load the package:

library(rlist)
#Code
x <- list(a=1,b=2,c=3)
list.reverse(x)

Output:

$c
[1] 3

$b
[1] 2

$a
[1] 1

Upvotes: 3

Related Questions