2016-08-08 100 views
-2

我有嵌套列表,例如:的R - 排序嵌套列表

x <- c(as.list(c("b", 4)), as.list(c("a", 4))) 

是否有可能通過在子列表第二元件訂購什麼?

+1

這給出了四個元素的列表。你的意思是'x < - list(as.list(c(「b」,4)),as.list(c(「a」,4)))'? – Psidom

+3

你的例子不好,但是'purrr :: sort_by'很好:'library(purrr); x < - list(list(「b」,4),list(「a」,3));在基礎上,'x [order(sapply(x,\'[[\',2))]' – alistaire

回答

0

我想你想以此爲例:

x <- c(list(c("b", 4)), list(c("a", 4)), list(c("b", 3))) 

和第二要素中的每個列表排序,你可以這樣做:

> x[ order (sapply(x, "[[", 2))] 
[[1]] 
[1] "b" "3" 

[[2]] 
[1] "b" "4" 

[[3]] 
[1] "a" "4" 

saplly(... , "[[" , <n>)模式往往是提取有用來自strsplit的結果:

> z <- strsplit(c("test of sentence reading", "another test", "something esle") , split=" ") 
> sapply(z, "[[", 2) 
[1] "of" "test" "esle"