R 按索引将一个列表中的值插入另一个列表

R 按索引将一个列表中的值插入另一个列表,r,R,我有两个列表x和y,还有一个索引向量,其中 x <- list(a = 1:4, b = letters[1:6]) y <- list(a = c(20, 50), b = c("abc", "xyz")) where <- c(2, 4) 我一直在尝试使用append,但它不起作用 lapply(seq(x), function(i) append(x[[i]], y[[i]], after = where[i])) #[[1]] #[1] 1 2 20 50 3

我有两个列表
x
y
,还有一个索引向量
,其中

x <- list(a = 1:4, b = letters[1:6])
y <- list(a = c(20, 50), b = c("abc", "xyz"))
where <- c(2, 4)
我一直在尝试使用
append
,但它不起作用

lapply(seq(x), function(i) append(x[[i]], y[[i]], after = where[i]))
#[[1]]
#[1]  1  2 20 50  3  4
#
#[[2]]
#[1] "a"   "b"   "c"   "d"   "abc" "xyz" "e"   "f"  
这是在错误的索引处追加的。另外,我希望在这个过程中保留列表名称。我也不知道
append
是否适合这个功能,因为我从来没有在任何地方使用过它


使用索引向量将值从一个列表插入另一个列表的最佳方法是什么?

在这里,我创建了一个
APPEND
函数,它是
APPEND
的迭代(通过
Reduce
)版本:

APPEND <- function(x, where, y)
   Reduce(function(z, args)do.call(append, c(list(z), args)),
          Map(list, y, where - 1), init = x)

一个
mapply
解决方案怎么样

x <- list(a = 1:4, b = letters[1:6])
y <- list(a = c(20, 50), b = c("abc", "xyz"))
where <- c(2, 4)

mapply(function(x,y,w) {
    r <- vector(class(x), length(x)+length(y))
    r[-w] <- x
    r[w] <- y
    r
}, x, y, MoreArgs=list(where), SIMPLIFY=FALSE)

这似乎是您想要的结果。

我不理解您的输出。“y”中的数据应该替换“x”中的数据,还是插入到这些索引中,但保留所有“x”?在给定的输出中,
$b
中的字母
b
已被替换,但字母
d
未被替换,并且
$a
中也有类似的内容。你能澄清一下吗。它在问题中说:)我想这是我感兴趣的
do.call,但我不太明白发生了什么。在
Reduce
中,什么是
z
?当然,它不是直接的,而是玩一下
Reduce
,你可能会得到它
Reduce(f,y,x)
x
开始,然后像这样迭代地替换它:
x
Map(APPEND, x, list(where), y)
x <- list(a = 1:4, b = letters[1:6])
y <- list(a = c(20, 50), b = c("abc", "xyz"))
where <- c(2, 4)

mapply(function(x,y,w) {
    r <- vector(class(x), length(x)+length(y))
    r[-w] <- x
    r[w] <- y
    r
}, x, y, MoreArgs=list(where), SIMPLIFY=FALSE)
$a
[1]  1 20  2 50  3  4

$b
[1] "a"   "abc" "b"   "xyz" "c"   "d"   "e"   "f"