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

Replace vector with indexes from list of positions

I have a vector of value:

y=c(2,3,4,4,3,2,1,1)

And a list of vector of positions:

l=list(c(1,2),c(2,3),c(3,4),c(4,5),c(5,6),c(6,7),c(7,8),c(8,1))

I’d like to replace the value of y by NAs (or other) for each of the element in the list l.

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

Expected output is a list of length length(l):

[[1]]
[1] NA NA  4  4  3  2  1  1

[[2]]
[1]  2 NA NA  4  3  2  1  1

[[3]]
[1]  2  3 NA NA  3  2  1  1

[[4]]
[1]  2  3  4 NA NA  2  1  1

[[5]]
[1]  2  3  4  4 NA NA  1  1

[[6]]
[1]  2  3  4  4  3 NA NA  1

[[7]]
[1]  2  3  4  4  3  2 NA NA

[[8]]
[1] NA  3  4  4  3  2  1 NA

Base R solutions are preferred.

>Solution :

We could either loop over the list, use the index to replace the values of ‘y’ to NA

lapply(l, \(x) replace(y, x, NA))
[[1]]
[1] NA NA  4  4  3  2  1  1

[[2]]
[1]  2 NA NA  4  3  2  1  1

[[3]]
[1]  2  3 NA NA  3  2  1  1

[[4]]
[1]  2  3  4 NA NA  2  1  1

[[5]]
[1]  2  3  4  4 NA NA  1  1

[[6]]
[1]  2  3  4  4  3 NA NA  1

[[7]]
[1]  2  3  4  4  3  2 NA NA

[[8]]
[1] NA  3  4  4  3  2  1 NA

Or another option is is.na<-

lapply(l, `is.na<-`, x = y)
[[1]]
[1] NA NA  4  4  3  2  1  1

[[2]]
[1]  2 NA NA  4  3  2  1  1

[[3]]
[1]  2  3 NA NA  3  2  1  1

[[4]]
[1]  2  3  4 NA NA  2  1  1

[[5]]
[1]  2  3  4  4 NA NA  1  1

[[6]]
[1]  2  3  4  4  3 NA NA  1

[[7]]
[1]  2  3  4  4  3  2 NA NA

[[8]]
[1] NA  3  4  4  3  2  1 NA
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