Reputation: 41
I have a vector which is like c(x, y, z)
, and lists like;
x <- list("a"= 2, "b"= 3)
y <- list("a"= 1, "c"= 4)
z <- list("a"= 3, "d"= 5)
which has the same names with elements of the initial vector. I want to sort the vector due to scores of "a" within lists.
The expected result is c(y, x, z)
.
Every help will be appreciated.
Upvotes: 2
Views: 87
Reputation: 886948
An option with map
library(tidyverse)
list(x, y, z) %>%
map_dbl(pluck, "a") %>%
order %>%
c('x', 'y', 'z')[.]
#[1] "y" "x" "z"
Upvotes: 0
Reputation: 3755
A base R
approach,
x <- list("a"= 2, "b"= 3)
y <- list("a"= 1, "c"= 4)
z <- list("a"= 3, "d"= 5)
v <- c("x", "y", "z")
names(sort(sapply(v, function(i){get(i)[["a"]]})))
gives,
"y" "x" "z"
Upvotes: 1
Reputation: 1525
You could do:
f <- list(x, y, z)
f[order(unlist(sapply(f, "[", "a")))]
Upvotes: 1