statespace
statespace

Reputation: 1664

R: Sorting list by values in nested list

Data is generated by similar process:

x <- rnorm(10)
y <- c("a", "b", "c") 
# chr vectors might have varying length and contents, simplified for sake of example
data_list <- list()
for(i in 1:length(x)) {
  data_list <- append(data_list, list(list(numeric = x[i], char = y)))
}

Basically, structure of generated list looks like:

$ :List of 2
  ..$ numeric: num 0.928
  ..$ char   : chr [1:3] "a" "b" "c"
 $ :List of 2
  ..$ numeric: num 1.4
  ..$ char   : chr [1:3] "a" "b" "c"
...

I would like to sort this list by numeric in ascending order, retaining initial structure.

I have tried solution explained here but it disrupts the structure of chr vectors.

Upvotes: 3

Views: 1287

Answers (3)

akrun
akrun

Reputation: 887691

Also:

data_list[order(unlist(do.call(`c`, data_list)[c(T,F)]))]

Upvotes: 0

asb
asb

Reputation: 4432

data_list = data_list[order(sapply(data_list, `[[`, i=1))]

Upvotes: 4

agstudy
agstudy

Reputation: 121608

For example:

data_list[order(rapply(data_list,"numeric",f=c))]

rapply intsruction will extract all numeric values, then we order them.

Upvotes: 0

Related Questions