【问题标题】:Insert specific elements in specific locations of a list在列表的特定位置插入特定元素
【发布时间】:2017-08-07 04:11:28
【问题描述】:

我的列表大小不等,我想将一个列表中的特定项目附加到另一个列表中的特定位置

第一个列表

dat <- structure(list(supergrp = c("D", "A", "P", "B"), 
               clusters = c("1", "2", "3", "1"), 
               items = structure(list(`1.2` = c("a", "c", "d"), 
                                      `2.1` = "b", `3` = "e", `4` = c("e", "b")),
                                 .Names = c("1.2", "2.1", "3", "4"))), 
          .Names = c("supergrp", "clusters", "items"), 
          row.names = c(NA, 4L), class = "data.frame")

第二个列表

val_to_append <- structure(list(supergrp = c("D", "A"), 
               clusters = c(1, 2), 
               items = structure(list(`1.2` = c("c", "f"), 
                                      `2.1` = c("c", "d", "e")), 
                                 .Names = c("1.2", "2.1"))), 
          .Names = c("supergrp", "clusters", "items"), 
          row.names = c(NA, -2L), class = "data.frame")

我想将val_to_append$item[[1]] 附加到dat$item[[3]] 同样,我想将项目val_to_append$item[[2]] 附加到dat$item[[1]]

需要的输出是

supergrp clusters      items
1        D        1 a, c, d, e
2        A        2          b
3        P        3    e, c, f
4        B        1       e, b

我可以循环执行此操作

dat_indx <- c(3,1)
val_indx <- c(1,2)

fin_result <- dat


for(i in seq_along(dat_indx)) {
  out_put_indx <- dat_indx[[i]]
  fin_result$items[[dat_indx[[i]]]] <- unique(c(fin_result$items[[dat_indx[[i]]]],
  val_to_append$items[[val_indx[[i]]]]))
} 

我尝试了正常的向量索引,例如

append(fin_result$items[[dat_indx]], val_to_append$items[[val_indx]])

没有成功。有没有一种有效的方法来做到这一点,因为我的列表,也就是数据框,有数十万个样本。 我正在考虑sapply,但没有具体的想法

【问题讨论】:

  • 有什么条件可以匹配吗?为什么val_to_append$item[[1]]需要附加到dat$item[[3]]而不是任何其他item
  • 我基本上已经计算了最相似的两个item和append之间的一对一距离。但为了使这项任务更容易,我们可以假设 dat_indx &lt;- c(3,1)val_indx &lt;- c(1,2) 可用作指定列表的哪个元素应附加到另一个列表中的哪个元素的映射。

标签: r list insert sapply


【解决方案1】:

我们可以使用mapply 来实现这一点。我们使用事先已知的索引值将值从val_to_append$items 附加到dat$items

dat_indx <- c(3,1)
val_indx <- c(1,2)

dat$items[dat_indx] <- mapply(function(x, y) 
   unique(c(dat$items[[x]], val_to_append$items[[y]])), dat_indx, val_indx)


dat
#  supergrp clusters      items
#1        D        1 a, c, d, e
#2        A        2          b
#3        P        3    e, c, f
#4        B        1       e, b

虽然,这是解决问题的另一种方法,但我怀疑它的效率如何。

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 2014-03-30
    • 2019-05-31
    • 2021-04-23
    • 1970-01-01
    • 2020-03-07
    相关资源
    最近更新 更多