Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 ?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading