2

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?

ashchk
  • 161
  • 13
climsaver
  • 341
  • 2
  • 15
  • `cbind`? I think you just want to "bind" them by "c"olumns, right? – cory Sep 11 '20 at 11:51
  • 1
    `do.call(data.frame, mget(ls(pattern = "T\\.vec_")))` – Ritchie Sacramento Sep 11 '20 at 11:53
  • How you created the vectors? Eventually at that point you can use a list. – jogo Sep 11 '20 at 11:55
  • I created the vectors by using assign in a for loop: `for (i in 1:8) { assign(paste0("T.slice_", i), T.array[,,i]) assign(paste0("T.vec_", i), as.vector(get(paste("T.slice_",i, sep="")))) assign(paste0("WRFdf_", i), data.frame(cbind(lonlat,get(paste("T.vec_",i, sep=""))))) }` Would there be a possibility to use a list at some point? – climsaver Sep 11 '20 at 12:04
  • yes, e.g. `sapply(1:8, function(i) as.vector(T.array[,,i]))` - this will put the vectors in a matrix (if possible). If you want a list, you can use `lapply(1:8, function(i) as.vector(T.array[,,i]))` – jogo Sep 11 '20 at 12:43
  • or eventually you can use `matrix()`, e.g. `A <- array(1:12, c(2,3,4)); matrix(A, 2*3, 4)` To reorder the dimensions of an array you can use `aperm()` – jogo Sep 11 '20 at 12:56
  • 1
    `sapply` did the job perfectly too and is probably the most efficient way. Thanks for that! – climsaver Sep 11 '20 at 14:30

1 Answers1

2

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)))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213