SHADJI
SHADJI

Reputation: 1

Create a new vector by appending elements between them in R

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

Upvotes: 0

Views: 57

Answers (1)

Ma&#235;l
Ma&#235;l

Reputation: 52089

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)

Upvotes: 1

Related Questions