所以,我有一个列表,每个元素都是一个向量。我有另一个因素向量,我想用它来合并我的一些列表元素。例如,这里有一些数据:
> l <- list("0"=c("a", "b", "c", "a", "a"), "1"=c("c", "b", "c", "a", "c", "c", "c"), "2"=c("b", "b", "b"), "3"=c("d", "d", "a", "b", "d"))
> l
$`0`
[1] "a" "b" "c" "a" "a"
$`1`
[1] "c" "b" "c" "a" "c" "c" "c"
$`2`
[1] "b" "b" "b"
$`3`
[1] "d" "d" "a" "b" "d"
> f <- factor(c(1,2,2,1))
> f
[1] 1 2 2 1
Levels: 1 2
所以根据这个因素,我想合并元素(1,4)和(2,3),因为它们具有相同的因子标签。我的最终名单应如下所示:
list.final:
$`0`
[1] "a" "b" "c" "a" "a" "d" "d" "a" "b" "d"
$`1`
[1] "c" "b" "c" "a" "c" "c" "c" "b" "b" "b"
因此,只有两个元素,从而合并原始列表中的元素1,4和2,3。有没有办法使用一些应用函数来做到这一点?
答案 0 :(得分:2)
tapply(l, f, FUN=unlist,use.names=F)
#$`1`
#[1] "a" "b" "c" "a" "a" "d" "d" "a" "b" "d"
#$`2`
#[1] "c" "b" "c" "a" "c" "c" "c" "b" "b" "b"
答案 1 :(得分:1)
您可以在因子上拆分列表,然后递归调用c
:
> lapply(split(l, f), function(x) unname(c(x, recursive = TRUE)))
$`1`
[1] "a" "b" "c" "a" "a" "d" "d" "a" "b" "d"
$`2`
[1] "c" "b" "c" "a" "c" "c" "c" "b" "b" "b"
以类似的方式使用unlist
> lapply(split(l, f), function(x) unname(unlist(x)))
$`1`
[1] "a" "b" "c" "a" "a" "d" "d" "a" "b" "d"
$`2`
[1] "c" "b" "c" "a" "c" "c" "c" "b" "b" "b"
答案 2 :(得分:0)
由于您只有两个级别,因此可以使用列表索引。
> L <- unname(l)
> list(`0` = unlist(L[f == 1]), `1` = unlist(L[f != 1]))
$`0`
[1] "a" "b" "c" "a" "a" "d" "d" "a" "b" "d"
$`1`
[1] "c" "b" "c" "a" "c" "c" "c" "b" "b" "b"