0

I am working in R.

I have n objects all named x followed by a number j = 1,..., n.

eg, for n = 5:

x1, x2, x3, x4, x5

I want to be able to list them all together dynamically depending on the n value:

list(x1,x2,x3,x4,x5)

In other words, I need to write a function that returns a list of those similarly-named objects automatically recognizing at what value of n to stop.

I tried this:

l <- vector()
for (k in (1:n)){
    if (k != n){
        u <- paste0("x",k, ",")
    } else {
        u <- paste0("x",k)
    }
    l <- append(l,u)
}

But obviously returns a list of characters...

Does anyone have an idea of how to do that?

Many thanks for your help.

Vitomir
  • 295
  • 2
  • 14

2 Answers2

2

mget gets a list of objects from their names. Construct the names using paste (vectorized), give it to mget (also vectorized) and you have your list:

l <- mget(paste0("x", 1:n))

I'd suggest trying to use lists from the start, rather than creating a bunch of objects then gathering them into a list. My answer at How to make a list of data frames has examples and discussion about this.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
0

If you want to write a function:

> x1 <- 1:2
> x2 <- 1:3
> x3 <- 2:5
> 
> make_list <- function(n){
+             l <- list()
+             for(i in 1:n){
+             l[[i]] <- get(paste0('x',i))
+   }
+   l
+ }
> make_list(3)
[[1]]
[1] 1 2

[[2]]
[1] 1 2 3

[[3]]
[1] 2 3 4 5

> make_list(1)
[[1]]
[1] 1 2

> 
Karthik S
  • 11,348
  • 2
  • 11
  • 25