Home > Mobile >  Create a new vector by appending elements between them in R
Create a new vector by appending elements between them in R

Time:06-19

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

CodePudding user response:

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)

CodePudding user response:

Thanks a lot for the accumulate solution from purr package. Is it possible to increment the vector with a specified number of elements?

In fact, I'm working with a vector 16000 genes. I'm trying to write a for loop where at each iteration, 100 genes should be knocked out from the data set and proceed some clustering analysis (clustering with 16000 genes, clustering with 15900 genes, clustering with 15800 genes, etc.) My idea is to make a list from the vector where each element of it is a vector of genes incremented by 100 (first element 100 genes, second element 200 genes, third element 300 genes and the 160th element, the total 16000 genes).
With accumulate (), I can increment one by one only between two following elements. Is there a way to make it increment 100 by hundred?

Thank you all once again for your help

  • Related