Home > Net >  How to order a nested list in R
How to order a nested list in R

Time:01-06

I need the code to be in R Exemple I have a list:

[[0,'A',50.1],
[1,'B',50.0],
[2,'C',50.2],
[3,'D',50.7],
[4,'E',50.3]]

I want to order it based on the 3rd elemnts only so I get a result like this

[[1,'B',50.0],
[0,'A',50.1],
[2,'C',50.2],
[4,'E',50.3],
[3,'D',50.7]]

and then reorder the index so the Final result would be

Final = [[0,'B',50.0],
[1,'A',50.1],
[2,'C',50.2],
[3,'E',50.3],
[4,'D',50.7]]

and then I have the indexes in some grouping

G = [[0,1],[1,3][2,3,4]]

I want based on G as indexes of Final have the Grouping like this

[['B','A'],['A','E']['C','E','D']]

I already have the code in python, but I need the same code in R

L = [[i, *x[1:]] for i, x in enumerate(sorted(L, key=lambda x: x[2]))]
print (L)
[[0, 'B', 50.0], [1, 'A', 50.1], [2, 'C', 50.2], [3, 'E', 50.3], [4, 'D', 50.7]]
out = [[L[y][1] for y in x] for x in G]
print (out)
[['B', 'A'], ['A', 'E'], ['C', 'E', 'D']]

CodePudding user response:

You can try:

LL <- L |>
  as.data.frame() |>
  arrange(x) |>
  mutate(id=sort(L$id))

lapply(G, \(x) LL$v1[LL$id %in% x])

[[1]]
[1] "B" "A"

[[2]]
[1] "A" "E"

[[3]]
[1] "C" "E" "D"

Data:

L <- list(id=0:4, v1=LETTERS[1:5], x = c(50.1, 50.0, 50.2, 50.7, 50.3))
G <- list(c(0,1), c(1,3), c(2,3,4))

Libraries:

library(dplyr)
  • Related