I would like to create a list of vectors. The first vector should contain only the first value specified, while the second value should contain the first and second and so on. This is obviously very manageable for a small number of values but I have a large number of values I would like to do this for.
For example:
vec_numbers <- c(1, 2, 3, 4, 5)
Will result in five vectors
vec1 <- 1
vec2 <- c(1,2)
vec3 <- c(1,2,3)
vec4 <- c(1,2,3,4)
vec5 <- c(1,2,3,4,5)
finallist <- list(vec1, vec2, vec3, vec4, vec5)
I would also like to do this for character vectors, not just numeric.
CodePudding user response:
If you want to create a list of such a sequence then you could use
mapply(seq,1,vec_numbers)
[[1]]
[1] 1
[[2]]
[1] 1 2
[[3]]
[1] 1 2 3
[[4]]
[1] 1 2 3 4
[[5]]
[1] 1 2 3 4 5
CodePudding user response:
vec_numbers <- c(1, 2, 3, 4, 5)
finallist <- list()
for(i in seq_along(along.with = vec_numbers)){
finallist[[i]] <- vec_numbers[1:i]
}
finallist
[[1]]
[1] 1
[[2]]
[1] 1 2
[[3]]
[1] 1 2 3
[[4]]
[1] 1 2 3 4
[[5]]
[1] 1 2 3 4 5
CodePudding user response:
vec_numbers <- c(1, 2, 3, 4, 5)
vec_chars <- c("hello", "how", "are", "you", "?")
chunk_vec <- function(vec){
return(
lapply(
seq_along(
vec
),
function(i){
vec[seq_len(i)]
}
)
)
}
chunk_vec(vec_numbers)
chunk_vec(vec_chars)
CodePudding user response:
Using sequence
with split
.
tmp <- sequence(vec_numbers)
split(tmp, cumsum(tmp == 1))
#$`1`
#[1] 1
#$`2`
#[1] 1 2
#$`3`
#[1] 1 2 3
#$`4`
#[1] 1 2 3 4
#$`5`
#[1] 1 2 3 4 5
CodePudding user response:
I like the map function in the purrr package. In the long run it would help in using with various kinds of inputs, and creating different kinds of outputs. look at the different map functions in the purrr package
For the given question, here's a quick solution. I have used 1000 numbers as input.
library(purrr)
vec_numbers <- 1:1000
result <- map(vec_numbers, function(x){1:x})
> result
[[1]]
[1] 1
[[2]]
[1] 1 2
[[3]]
[1] 1 2 3
[[4]]
[1] 1 2 3 4
..