I’m trying to create a function in R that takes a list as an input and reorder its elements based on the mean of each element (for example, the first element will be the one with the largest mean value, etc.) I’m trying to find the easiest way to do it without having to use any loops. I tried to sort the mean like below but couldn’t figure out how to have the elements associated with the mean to move along. Any suggestions or advice would be appreciated.
function1 <- function(x){
return(sort(mean(x), decreasing = T))
}
function2 <- function(x) {
return(lapply(function1, x))
}
testlist <- list(c(10, 5, 1), c(3, 2), c(77, 90, 1), c(23, 34), c(2, 35, 22))
function2(testlist)
>Solution :
Here’s one way that is really just testlist[order(sapply(testiest, mean))]
, but put inside a function. The idea is that sapply()
returns a vector that gives the mean of each list element, order()
gives the element numbers in order of the mean. Then, you are giving that ordered element numbers based on the mean to index the values of the list.
testlist <- list(c(10, 5, 1), c(3, 2), c(77, 90, 1), c(23, 34), c(2, 35, 22))
function1 <- function(x){
x[order(sapply(x, mean))]
}
function1(testlist)
#> [[1]]
#> [1] 3 2
#>
#> [[2]]
#> [1] 10 5 1
#>
#> [[3]]
#> [1] 2 35 22
#>
#> [[4]]
#> [1] 23 34
#>
#> [[5]]
#> [1] 77 90 1
Created on 2023-02-18 by the reprex package (v2.0.1)