将命名向量转换为 R 中的列表 [英] Convert named vector to list in R

查看:27
本文介绍了将命名向量转换为 R 中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下命名的数字向量:

Suppose I have the following named numeric vector:

a <- 1:8
names(a) <- rep(c('I', 'II'), each = 4)

如何将此向量转换为长度为 2 的列表(如下所示)?

How can I convert this vector to a list of length 2 (shown below)?

a.list
# $I
# [1] 1 2 3 4
# $II
# [1] 5 6 7 8

注意 as.list(a) 不是我要找的.我非常不满意(对于大向量也很慢)的解决方案是:

Note that as.list(a) is not what I'm looking for. My very unsatisfying (and slow for large vectors) solution is:

names.uniq <- unique(names(a))
a.list <- setNames(vector('list', length(names.uniq)), names.uniq)
for(i in 1:length(names.uniq)) {
  names.i <- names.uniq[i]
  a.i <- a[names(a)==names.i]
  a.list[[names.i]] <- unname(a.i)
}

预先感谢您的帮助,德文

Thank you in advance for your help, Devin

推荐答案

就像我在评论中所说的,你可以使用 split 来创建一个列表.

Like I said in the comment, you can use split to create a list.

a.list <- split(a, names(a))
a.list <- lapply(a.list, unname)

单线将是

a.list <- lapply(split(a, names(a)), unname)
#$I
#[1] 1 2 3 4
#
#$II
#[1] 5 6 7 8

编辑.
然后,thelatemail 在他的评论中发布了对此的简化.我已经使用 Devin King 的方式对它计时,它不仅更简单,速度也提高了 25%.

EDIT.
Then, thelatemail posted a simplification of this in his comment. I've timed it using Devin King's way and it's not only simpler it's also 25% faster.

a.list <- split(unname(a),names(a))

这篇关于将命名向量转换为 R 中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆