Search code examples
rvector

How to consecutively concatenate a vector of integers in R


vec <- c(1, 3, 2, 37)

I want to consecutively concatenate this vector such that the output looks something like this:

> output
[[1]]
[1] 1

[[2]]
[1] 1 3

[[3]]
[1] 1 3 2

[[4]]
[1] 1 3 2 37

I wrote a function to do this, but it didn't give me the correct output:

myfun <- function(vec){
  output = vector("list", length(vec))
  output[[1]] = vec[1]
  for(i in 2:length(vec)){
    output[[i]] = paste(output[[i - 1]], vec[i])
    output[[i]] = as.numeric(strsplit(output[[i]], " ")[[1]])
  }
  return(output)
}
> myfun(c(1, 3, 2, 37))
[[1]]
[1] 1

[[2]]
[1] 1 3

[[3]]
[1] 1 2

[[4]]
[1]  1 37

Solution

  • A direct way to do this would be Reduce:

    Reduce(f = c,x = vec,accumulate = TRUE)
    

    There's a purrr::accumulate function what will accomplish the same thing:

    purrr::accumulate(.x = vec,.f = c,.simplify = FALSE)
    

    (Edited to incorporate the comment to just use c() as the function, much simpler.)