Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace vector elements with indexes from list of positions

Tags:

list

r

apply

I have a vector of values:

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

And a list of vectors 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.

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.

like image 550
Maël Avatar asked Dec 24 '21 17:12

Maël


People also ask

How do you change the position of an element in a vector?

Insert will mean adding an element at a location and moving all subsequent elements up one place in the vector (ie growing the vector by one element). On the other hand you can use setting to indicate you want to change an existing vector element to a new value.

How do you change the index value of a list?

We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable 'i'. Then, we replace that item with a new value using list slicing.

Can vectors be indexed?

Indexing works on Vectors, So just Acces it by using index.

How do you replace an element in a vector in R?

To replace a value in an R vector, we can use replace function. It is better to save the replacement with a new object, even if you name that new object same as the original, otherwise the replacements will not work with further analysis.


Video Answer


1 Answers

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
like image 169
akrun Avatar answered Oct 26 '22 07:10

akrun