How to create a data frame from multiple vectors?

Viewed 240

I have 8 vectors with the same pattern in their names: T.vec_1, T.vec_2, ..., T.vec_8. They are all of the same length. Now I want to create a data frame that consists of those 8 vectors.

Of course there is this option, which is not very elegant and does not make sense if there is a higher number of vectors:

df <- data.frame(T.vec_1, T.vec_2, T.vec_3, T.vec_4, T.vec_5, T.vec_6, T.vec_7, T.vec_8)

That is why I tried to do it by using a loop in two ways, which both did not work out:

for (i in 1:8) {
  df <- data.frame(get(paste("T.vec_", i, sep = "")))
}

and

for (i in 1:8) {
  assign(df), data.frame(get(paste("T.vec_",i,sep="")))
}

What is the proper and smart way to do it?

1 Answers

You can use mget to get multiple vectors in a list and bind them by columns :

dplyr::bind_cols(mget(paste0('T.vec_', 1:8)))
#bind_rows works too.
#dplyr::bind_rows(mget(paste0('T.vec_', 1:2)))

Or in base R :

do.call(cbind.data.frame, mget(paste0('T.vec_', 1:8)))
Related