Daniel Mendoza
Daniel Mendoza

Reputation: 43

Paste Vectors without `rbind` function

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.

Upvotes: 2

Views: 107

Answers (2)

Jilber Urbina
Jilber Urbina

Reputation: 61154

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)

Upvotes: 5

struggles
struggles

Reputation: 865

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)

Upvotes: 0

Related Questions