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

Time:06-02

How to assign each element of a vector to the last element of several other vectors in one line ?
Or more generally, same question but replace "last element" with "i-th element".

# 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 ?

CodePudding user response:

We can get the objects in a list and replace

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

-output

> targ1
[1] 1 2 3 5
> targ2
[1] 1 2 3 1
> targ3
[1] 1 2 3 2
  •  Tags:  
  • r
  • Related