簡體   English   中英

如何基於[in R]中包含的值的順序對向量列表進行排序

[英]How to order a list of vectors based on the order of values contained within [in R]

我有以下對象:

L <- list(4, 7, c(3, 1), c(1, 2), c(5, 6))
> L
[[1]]
[1] 4

[[2]]
[1] 7

[[3]]
[1] 3 1

[[4]]
[1] 1 2

[[5]]
[1] 5 6

我想根據每個值的出現對它們進行重新排序,以使那些包含1的向量排在最前面,而向量1,21,3之前1,3 我想要的結果是:

[[1]]
[1] 1 2

[[2]]
[1] 3 1

[[3]]
[1] 4

[[4]]
[1] 5 6

[[5]]
[1] 7

在此先感謝您的幫助!

編輯:

這是一個更復雜的情況:

L <- list(7, c(9, 20), c(2, 3), c(10, 17), c(1, 12, 14), c(1, 3, 5, 
12), c(8, 9, 18, 19), c(6, 11, 15, 16, 17), c(4, 6, 11, 13, 15, 
16))
L[order(sapply(L,function(x)paste0(sort(x),collapse=".")))]
# [[1]]
# [1] 1 2
#
# [[2]]
# [1] 3 1
# 
# [[3]]
# [1] 4
# 
# [[4]]
# [1] 5 6
#
# [[5]]
# [1] 7

這將適用於最多n位數字的整數:

L <- list(4, 7, c(3, 1), c(20, 10), c(5, 6))
library(stringr)
n <- 5
L[order(sapply(L,function(x)paste0(str_pad(sort(x),n,pad="0"),collapse=".")))]
L[sort(sapply(L, '[[', 1), index.return = T)$ix]

這涉及更多,但我相信它將起作用

ml<-max(sapply(L, length))
reord<-do.call(order, data.frame(
    do.call(rbind, 
        lapply(L, function(x) c(sort(x), rep.int(0, ml-length(x))))
    )
))
L[reord]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM