Split a vector into multiple vectors in R -


i want split 1 vector(x) multiple vectors(x1, x2 ,... , xn).

my input: x <- 1:10

my desire output:

x1 <- c(1,2,3,4) x2 <- c(2,3,4,5) x3 <- c(3,4,5,6) x4 <- c(4,5,6,7) x5 <- c(5,6,7,8) x6 <- c(6,7,8,9) x7 <- c(7,8,9,10) 

my code(thanks mrs.richard herron inspiration):

x <- 1:10 n <-3 vectors <- function(x, n) split(x, sort(rank(x) %% n)) vectors(x,n) 

thanks much!

we can use lapply loop on sequence of 'x' such have length of 4 in each of elements in list, create sequence (:) index index + n, subset 'x'. if needed have individual vectors, set names of list , use list2env.

n <- 3 lst <- lapply(1:(length(x)-n), function(i) x[i:(i+n)]) names(lst) <- paste0("x", seq_along(lst)) list2env(lst, envir = .globalenv) x1 #[1] 1 2 3 4 x2 #[1] 2 3 4 5 x3 #[1] 3 4 5 6 

or can create matrix instead of multiple vectors in global environment each row corresponds vector of interest

matrix(x[1:4] + rep(0:6, each = 4), ncol=4, byrow = true) 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -