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.
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.
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.
Indexing works on Vectors, So just Acces it by using index.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With