我想根据每个元素中“ a”的数量对列表进行排序。
library("purrr")
data1 <- c("apple","appreciate","available","account","adapt")
data2 <- c("tab","banana","cable","tatabox","aaaaaaa")
list1 <- list(data1,data2)
ca <- lapply(list1, function(x) str_count(x, "a"))
t2 <- Map(split, list1, ca)
t3 <- transpose(t2)
> t3
$`1`
$`1`[[1]]
[1] "apple" "account"
$`1`[[2]]
[1] "tab" "cable"
$`2`
$`2`[[1]]
[1] "appreciate" "adapt"
$`2`[[2]]
[1] "tatabox"
$`3`
$`3`[[1]]
[1] "available"
$`3`[[2]]
[1] "banana"
它丢失了data2中的“ aaaaaaa”。我该如何解决这个问题?
我找到了解决方法:
data1 <- c("apple","appreciate","available","account","adapt")
data2 <- c("tab","banana","cable","tatabox","aaaaaaa","aaaaaaaaaaa")
list1 <- list(data1,data2)
ca <- lapply(list1, function(x) str_count(x, "a"))
k11<- flatten(Map(split, list1, ca))
k1<-split(k11, as.integer(names(k11)))
答案 0 :(得分:3)
引用lionel的单词:“ transpose()
将列表的列表视为隐式矩形表”。它不是为像当前这样的许多边缘情况设计的。但是,您可以将较长的查询放在开头:transpose(t2[2:1])
。
但是,此解决方法无法推广。我更喜欢以下方式---将子列表合并为一个列表,然后再次拆分:
> t3 <- do.call(c, t2)
> split(t3, names(t3))
$`1`
$`1`$`1`
[1] "apple" "account"
$`1`$`1`
[1] "tab" "cable"
$`2`
$`2`$`2`
[1] "appreciate" "adapt"
$`2`$`2`
[1] "tatabox"
$`3`
$`3`$`3`
[1] "available"
$`3`$`3`
[1] "banana"
$`7`
$`7`$`7`
[1] "aaaaaaa"
用于命名和未命名输入的函数:
data1 <- c("apple","appreciate","available","account","adapt")
data2 <- c("tab","banana","cable","tatabox","aaaaaaa","aaaaaaaaaaa")
list1 <- list(data1,data2)
names(list1) <- c("atf","bdfs")
f <- function(x){
if(is.null(names(x))){
names(x) <- make.names(seq_along(x))
}
dtf <- stack(x)
res <- split(dtf, str_count(dtf$values, 'a'))
lapply(res, function(y) split(y$values, y$ind, drop = TRUE) )
}
f(list1)
答案 1 :(得分:1)
我们也可以使用带有purrr
函数的管道
map(list1, str_count, "a") %>%
map2(list1, ., split) %>%
flatten %>%
split(names(.))
#$`1`
#$`1`$`1`
#[1] "apple" "account"
#$`1`$`1`
#[1] "tab" "cable"
#$`2`
#$`2`$`2`
#[1] "appreciate" "adapt"
#$`2`$`2`
#[1] "tatabox"
#$`3`
#$`3`$`3`
#[1] "available"
#$`3`$`3`
#[1] "banana"
#$`7`
#$`7`$`7`
#[1] "aaaaaaa"