简体   繁体   中英

split a vector and fill every other element in order to have specific length

I have a vector which I split into some parts, I compute the mean of every part and then I want to have a vector with the original length which will contain the mean values and between them fill with NA.

vec <- c(1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000)
s <- 2

parts <- split(vec, rep(1:s, ceiling(length(vec) / s),
              length.out = length(vec)))

the_mean <- lapply(parts, mean)
res <- unlist(the_mean)

res <- replace(NA * s, seq(from = 1 , to = length(vec), length = length(res)), res)
res

The result I receive now is:

4000 NA NA NA NA NA NA 5000

I want to receive:

4000 NA NA 5000 NA NA NA NA

because the splitting is done by s <-2 , so I have the first mean (4000) and after 2 values, I must have the second mean (5000). The rest vector should be filled with NA. The reason is that I want the result vector to have the same length as the initial (vec).

If for example, s = 3 , then the result should be:

4000 NA NA NA 5000 NA NA 4500 .

Note, that between 5000 and 4500 we have 2 NA and not 3 since the vector size is 8.

Here is one way to do it:

apply_fun <- function(vec, s) {
   #Initialize the vector with NA
   ans <- rep(NA, length(vec))
   #Create groups to calculate mean
   groups <- rep(1:s, ceiling(length(vec) / s),length.out = length(vec))
   #Create indices to place mean of each group
   vals <- pmin(seq(1, by = s + 1, length.out = s), length(vec))
   #Assign mean values at those indices
   ans[vals] <- tapply(vec, groups, mean)
   #Return the final answer
   return(ans)
}

apply_fun(vec, 2)
#[1] 4000   NA   NA 5000   NA   NA   NA   NA

apply_fun(vec, 3)
#[1] 4000   NA   NA   NA 5000   NA   NA 4500

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM