Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Vectors using a Loop

Tags:

loops

r

vector

If I have vectors m1, m2, ... m"n" and I want to create a vector that includes all of the values, how would I go about this?

For example:

m1 = c(0, 2, 4) 
m2 = c(1, 4)
m3 = (3)

I want a vector "totalmods" which outputs {0, 2, 4, 1, 4, 3}

My attempt where nummod is "n", the vector with the largest number was:

for(i in 1:nummod){
  totalmods <- c(paste("m",i, sep = ""))
}

Thanks for your help!

like image 291
ReidD Avatar asked Jul 27 '26 19:07

ReidD


1 Answers

You can use mget and unlist

unlist(mget(ls(pattern = "^m\\d+$")), use.names = FALSE)
# [1] 0 2 4 1 4 3

We create a list with all objects whose names start with "m" (^m) and end with one or more digit (\\d+$). We use unlist to create a vector.


A user asked for a benchmark in the comments (and I became curious)

x <- 2:2000
y <- setNames(lapply(x, seq_len),  paste0("m", x))

library(microbenchmark)
microbenchmark(markus = unlist(y, use.names = FALSE),
               tmfmnk = Reduce(c, y),
               akrun = purrr::flatten_dbl(y)
               times = 10L)
#Unit: milliseconds
#   expr       min        lq       mean    median        uq       max neval
# markus   13.7329   13.8566   22.09223   13.9139   14.1638   75.9402    10
# tmfmnk 3427.3571 3614.2938 3761.36990 3806.0890 3928.1482 4004.7853    10
# akrun    42.7355   64.4865   153.8598  148.5418  240.0674  286.8956    10
like image 84
markus Avatar answered Jul 29 '26 10:07

markus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!