基于数据框匹配行数重复R语言三重嵌套列表的实现问题
R语言:按数据框行重复嵌套列表指定子列表并保留其余部分
需求说明
根据数据框mydf中同名行的数量,重复三重嵌套列表megalist内的list.A子列表(例如list.A的a因mydf中有3行a重复3次,b因2行b重复2次,c因1行c重复1次),同时保留list.B等其他部分的原有结构与内容。
示例数据
三重嵌套列表megalist
list.A <- list(a = c(1,2,5,6), b = c(2,4,6,5), c = c(2,4,2,5)) list.B <- list(a = c(7,7,7,7), b = c(8,8,8,8), c = c(9,9,9,9)) weights <- list(list.A, list.B) names(weights) <- c("list.A", "list.B") list.A <- list(a = c(2,2,2,2), b = c(3,3,3,3), c = c(4,4,4,4)) list.B <- list(a = c(5,5,5,5), b = c(6,6,6,6), c = c(7,7,7,7)) scores <- list(list.A, list.B) names(scores) <- c("list.A", "list.B") megalist <- list(weights, scores) names(megalist) <- c("weights", "scores")
数据框mydf
mydf <- as.data.frame(c("a", "a", "a", "b", "b", "c")) colnames(mydf) <- "Freq"
已尝试的错误实现
- 第一种代码:直接提取
list.A的重复部分,丢失了list.B
megalist.repeated <- lapply(megalist, function(x, new) { x[["list.A"]][new] }, new = mydf$Freq)
- 第二种代码:
if语句逻辑错误,返回长度为0的结果
megalist.repeated <- lapply(megalist, function(x, y) if(x[["y"]]=="list.A") lapply(y, function (y, new) { y[new] }, new = mydf$Freq ) else y)
正确解决方案
核心思路:遍历megalist的顶层元素(weights和scores),仅修改其中的list.A部分为重复后的内容,其余部分保持原样。
# 生成目标嵌套列表 megalist.repeated <- lapply(megalist, function(item) { # 对当前顶层元素中的list.A进行重复处理 item$list.A <- item$list.A[mydf$Freq] # 返回修改后的顶层元素,保留其他部分 item })
验证结果
查看处理后的list.A结构:
# 查看weights下的list.A,已按mydf的行重复对应子元素 megalist.repeated$weights$list.A
输出会包含3个a、2个b、1个c子列表,而list.B的结构与内容完全保留:
# 查看weights下的list.B,无变化 megalist.repeated$weights$list.B
内容的提问来源于stack exchange,提问作者simpson
相关产品推荐
相关产品推荐

