You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于名称向量与唯一向量列表生成命名列表的R实现方法

问题描述

我有一个整数类型的非语法名称向量nms、一个唯一向量列表un_vecs,希望将un_vecs中的每个元素按reps指定的次数重复,生成一个以nms为名称、长度等于length(nms)的命名列表,该如何实现?

输入示例

nms <- 1:5
un_vecs <- list(letters[1:3], letters[2:7])
reps <- c(2, 3)

预期输出

list(
  `1` = un_vecs[[1]],
  `2` = un_vecs[[1]],
  `3` = un_vecs[[2]],
  `4` = un_vecs[[2]],
  `5` = un_vecs[[2]]
)

打印结果如下:

# $`1`
# [1] "a" "b" "c"
# 
# $`2`
# [1] "a" "b" "c"
# 
# $`3`
# [1] "b" "c" "d" "e" "f" "g"
# 
# $`4`
# [1] "b" "c" "d" "e" "f" "g"
# 
# $`5`
# [1] "b" "c" "d" "e" "f" "g"

解决方案

方法1:基础R原生实现

利用rep()生成重复的索引序列,提取对应列表元素后设置名称即可:

# 生成重复的元素索引,提取对应列表项
result <- un_vecs[rep(seq_along(un_vecs), reps)]
# 为结果列表设置名称
names(result) <- nms

方法2:tidyverse风格实现(依赖purrr包)

如果习惯函数式编程风格,可用purrr包的map()函数完成:

library(purrr)

# 按重复索引提取元素
result <- map(rep(seq_along(un_vecs), reps), ~un_vecs[[.]])
# 设置名称
names(result) <- nms

两种方法都能得到符合预期的命名列表,基础R方法无需额外安装包,更轻量化;purrr方法则更贴合tidyverse生态的编程习惯。

内容的提问来源于stack exchange,提问作者Maël

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 01:59:52