2

I have 10 Vectors in my R environment. I want to paste this vectors for create a data frame. I used the rbind function, but i think that is very inefficient, because i have to type all variables in the function. The question is, can i use the paste0 or paste function or other function like that, for paste this vectors?, thank you.

#Por ejemplo

x1 <- c(1, 2)
x2 <- c(3, 4)
x3 <- c(5, 6)
x4 <- c(7, 8)
x5 <- c(9, 10)
x6 <- c(11, 12)
x7 <- c(13, 14)
x8 <- c(15, 16)
x9 <- c(17, 18)
x10 <- c(19, 30)

rbind(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10)

I want to paste this vectors, without rbind, with some function like paste0 or paste.

  • Why not use `rbind`? What do you mean `paste` which is reserved for character objects? Please show desired output. – Parfait Oct 05 '18 at 17:29
  • 2
    The issue is that you create a bunch of sequentially named variables. Don't do that. Put them in a data structure, like a data frame or a list, from the very beginning. – Gregor Thomas Oct 05 '18 at 17:56

2 Answers2

5

The do.call function is useful when the argument is a list and the function is expecting items that are just vectors. Since mget, which returns a list, is the natural tool when attempting to go from character to object names, you might try:

do.call(rbind, mget(paste0("x", 1:10)))
#---
    [,1] [,2]
x1     1    2
x2     3    4
x3     5    6
x4     7    8
x5     9   10
x6    11   12
x7    13   14
x8    15   16
x9    17   18
x10   19   30

Or using matrix

matrix(unlist(mget(paste0("x", 1:10))), ncol=2, byrow = TRUE)
IRTFM
  • 258,963
  • 21
  • 364
  • 487
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • 3
    @Parfait Imo, it is fine. OP should know how to look up help files, but it wouldn't hurt to point to `?do.call` etc, I suppose. If anything is frowned on (by me), I guess it's the lack of admonition/critique to not make a bunch of vectors in the global environment like the OP has done (eg, throw in an "of course, it's silly" https://stackoverflow.com/a/25510018). Anyway, I guess further comments can go to https://chat.stackoverflow.com/rooms/25312/r-public – Frank Oct 05 '18 at 17:56
  • Thanks, it helped me a lot. – Daniel Mendoza Oct 09 '18 at 17:09
0

ls() returns a vector of all the variable names in your environment. If you do a regex for every variable name that begins with x then you can iterate over the new vector and get() them to call the variable with that name. If you call get in a lapply function, then you'll get a list of all the called variables. do.call() performs a function on every item in a list.

to_get <- ls()[grepl('^x', ls())]
to_bind <- lapply(to_get, get)
final_matrix <- do.call(rbind, to_bind)
struggles
  • 825
  • 5
  • 10