Search code examples
robjectvectornumeric

R creating vector from numbers that begin with the same string


I have multiple numbers in my environment

e.g.

num_1 <- 4
num_2 <- 6
num_3 <- 5
...
num_88 <- 19

I want create a vector of all the numbers where the value begins with "num_" without having to write out each number individually, Please let me know how to do that

so it would be

vec1
(4,6,5,..,19)

Thanks


Solution

  • We can use mget to get the object values in a list and then unlist to create the vector

    unlist(mget(ls(pattern = '^num_\\d+$')))
    

    Or use paste with mget

    unlist(mget(paste0("num_", 1:88)))