Home > Enterprise >  Replace vector with indexes from list of positions
Replace vector with indexes from list of positions

Time:12-25

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.

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.

CodePudding user response:

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

CodePudding user response:

Here is a base R solution with lapply.

lapply(l, \(x) {is.na(y) <- 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
  • Related