将向量的每个元素分配给 R 一行中几个其他向量的最后一个元素

Assign each element of a vector to the last element of several other vectors in one line in R

如何在一行中将一个向量的每个元素分配给其他几个向量的最后一个元素?
或者更一般地说,同样的问题,但将“最后一个元素”替换为“第 i 个元素”。

# Problem : assign each element of the root vector 
# to the last element of the target vectors
root <- c(5, 1, 2)
targ1 <- targ2 <- targ3 <- 1:4

# Solution 
i = length(targ1)
targ1[i] <- root[1]
targ2[i] <- root[2]
targ3[i] <- root[3]

# The previous solution works, but it's too verbose. 
# Is it possible to achieve this in one line or so ?

我们可以得到listreplace

中的对象
list2env(Map(\(x, y) replace(x, i, y), mget(ls(pattern = 'targ')), 
    root), .GlobalEnv)

-输出

> targ1
[1] 1 2 3 5
> targ2
[1] 1 2 3 1
> targ3
[1] 1 2 3 2