Poiu Rewq
Poiu Rewq

Reputation: 192

R extend vectors to be the same length around central value

Let's suppose I have a list:

[[1]]
 [1]  0.7125856 -1.4871811  0.6230076  1.0756424  0.8172592 -0.1327926 -0.7674947 -1.0738684  1.5706677
[10] -0.6674960

[[2]]
[1] -0.5778682 -1.1186447  0.8272505  0.5123162  0.6607654  1.6559877 -0.7961859 -0.8966686

[[3]]
 [1] -1.42867999 -0.21142100 -2.89762370  0.11036288  0.66846399 -0.77309213  0.35278541 -0.99579117 -0.73043142
[10] -0.01857864 -0.93654969  0.46751328

[[4]]
[1] -0.483896685 -0.207550362 -0.902920637 -0.008191134 -1.015636093

And I also have a vector with indices of so-called "central" values of vectors in this list:

[1] 2 4 5 1

What I'm trying to get is for given range (for example, 3) get subsets of vectors around those centers with the length of range in both sides. So every subset must be length of 7 and if range extends beyond length of vector there must be NAs added:

[[1]]
[1]         NA         NA  0.7125856 [-1.4871811]  0.6230076  1.0756424  0.8172592

[[2]]
[1] -0.5778682 -1.1186447  0.8272505  [0.5123162]  0.6607654  1.6559877 -0.7961859

[[3]]
[1] -0.2114210 -2.8976237  0.1103629  [0.6684640] -0.7730921  0.3527854 -0.9957912

[[4]]
[1]           NA           NA           NA [-0.483896685] -0.207550362 -0.902920637 -0.008191134

I put centers in brackets, because SO doesn't allow bold text in a code. Is there a way to do something like this in R?

Upvotes: 0

Views: 202

Answers (1)

Brian Davis
Brian Davis

Reputation: 992

I think you're looking for something like this?

Data:

n <- 10
x <- list(rnorm(n),rnorm(n),rnorm(n),rnorm(n))
i <- c(2,4,5,1)
r <- 3

Possible solution:

f <- function(x) ifelse((x-r):(x+r) %in% 1:n,(x-r):(x+r),NA)
tmp <- lapply(i,f)
out <- mapply("[",x,tmp)
split(out,col(out))
$`1`
[1]         NA         NA  0.8120232  0.4980624 -2.9708413  0.6754918 -0.9900322

$`2`
[1] -1.0303741 -1.7432638  0.9466315 -1.3322712 -1.7281613 -0.1951453  0.3789493

$`3`
[1] -1.4120119  0.3675425 -0.8378275 -1.1080856 -0.9369994  1.0823376  1.2194782

$`4`
[1]         NA         NA         NA  0.1757164 -1.5768032  0.3121876  0.4443616

Upvotes: 1

Related Questions