ReidD
ReidD

Reputation: 33

Combining Vectors using a Loop

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!

Upvotes: 3

Views: 67

Answers (3)

markus
markus

Reputation: 26343

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

Upvotes: 1

akrun
akrun

Reputation: 886938

An option with flatten

library(purrr)
mget(ls(pattern = "^m\\d+")) %>%
    flatten_dbl
#[1] 0 2 4 1 4 3

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 39858

One option could be:

Reduce(c, mget(ls(pattern = "^m\\d+")))

[1] 0 2 4 1 4 3

Upvotes: 0

Related Questions