如何合并两个R列表并为元素分配id与type键
实现方法
你可以通过以下两种方式实现需求:
方法一:使用base R原生函数
先从原列表中提取对应向量,再用mapply将两个向量的元素一一配对生成子列表:
# 提取向量 ids <- comb_test[[1]] types <- col_type_list[[1]] # 生成目标列表 common.list <- mapply(function(x, y) list(id = x, type = y), ids, types, SIMPLIFY = FALSE)
方法二:使用purrr包(tidyverse生态)
如果习惯使用tidyverse工具,可以用map2函数更直观地完成配对:
library(purrr) # 提取向量并生成目标列表 ids <- comb_test[[1]] types <- col_type_list[[1]] common.list <- map2(ids, types, ~list(id = .x, type = .y))
两种方法最终都会得到你需要的common.list结构:
# 输出结果 > common.list [[1]] [[1]]$id [1] 7 [[1]]$type [1] "bin" [[2]] [[2]]$id [1] 8 [[2]]$type [1] "bin"
内容的提问来源于stack exchange,提问作者GOGA GOGA
相关产品推荐
相关产品推荐

