按键分组列表[R]

时间:2017-06-09 08:12:33

标签: r list

我有一个列表:

mylist <- list("key 1" = 1,
           "key 1" = 2,
           "key 1" = 3)
mylist
> mylist
$`key 1`
[1] 1

$`key 1`
[1] 2

$`key 1`
[1] 3

我希望我的最终名单看起来像这样:

$`key 1`
[1] 1 2 3

谢谢!

1 个答案:

答案 0 :(得分:1)

使用取消列表

mylist <- list("key 1" = 1,
               "key 1" = 2,
               "key 1" = 3)

mylist2 <- list("key 1" = unlist(mylist,use.names=FALSE))

mylist2
# $`key 1`
# [1] 1 2 3

编辑:如果您有多个键,则为常规解决方案:

mylist <- list("key 1" = 1,
               "key 1" = 2,
               "key 1" = 3,
               "key 2" = 4,
               "key 3" = 4,
               "key 3" = 4,
               "key 4" = 4)

mylist2 <- tapply(unlist(mylist,use.names=FALSE), names(mylist),c)

# > mylist2
# $`key 1`
# [1] 1 2 3
# 
# $`key 2`
# [1] 4
# 
# $`key 3`
# [1] 4 4
# 
# $`key 4`
# [1] 4