0

I am a new to R programming. I need to find a way to create a list from a vector but each element should by appended with its following 100 elements; I thought about a for loop but I can't find a way to indicate the "next hundred elements". For example :

input:

a_vec<- c("ant","bee","mosquito","fly")
a_list <- list(("ant"),c("ant","bee"),c("ant","bee","mosquito"),c("ant","bee","mosquito","fly"))

output:

> a_vec
[1] "ant"      "bee"      "mosquito" "fly"     
> a_list
[[1]]
[1] "ant"

[[2]]
[1] "ant" "bee"

[[3]]
[1] "ant"      "bee"      "mosquito"

[[4]]
[1] "ant"      "bee"      "mosquito" "fly" 

Thanks in advance for your help

SHADJI
  • 1
  • 1
  • Do you want something like `lapply(seq_along(a_vec), function(i) a_vec[1:i])`? What exactly happens when the list gets longer than 100? Or maybe you want `lapply(seq_along(a_vec), function(i) a_vec[max(1, i-99):i])` instead? It's hard to say since your sample doesn't seem to interact with that particular requirement so it's hard to test. – MrFlick Jun 17 '22 at 13:50
  • I answered in the post my exact problem – SHADJI Jun 19 '22 at 07:52

1 Answers1

1

Use purrr::accumulate with c:

library(purrr)
a_vec <- c("ant","bee","mosquito","fly")

accumulate(a_vec, c)

# [[1]]
# [1] "ant"
# 
# [[2]]
# [1] "ant" "bee"
# 
# [[3]]
# [1] "ant"      "bee"      "mosquito"
# 
# [[4]]
# [1] "ant"      "bee"      "mosquito"       "fly"

Or, in base R, Reduce with accumulate = T:

Reduce(c, a_vec, accumulate = T)
Maël
  • 45,206
  • 3
  • 29
  • 67