1

I have 247 data frames which are sequentially named (y1, y2, y3, ...., y247). They are resulted from the following code:

for (i in (1:247)) {

  nam <- paste("y", i, sep = "")
  assign(nam, dairy[dairy$FARM==i,"YIT"])
}

I wish to cbind all of them to have:

df <- cbind(y1,y2,...,y247)

Can I do this with a loop without typing all 247 data frames?

Thanks

  • You might be able to store the data sets in a list `X <- split(dairy$YIT, dairy$FARM)` and then bind via `do.call(cbind, X)`. – stephematician Feb 29 '20 at 01:37
  • Why are you doing this? It looks like you already have all the data in a single data frame? Is `dairy[dairy$FARM %in% 1:247, "YIT"]` what you are looking for? – Kent Johnson Feb 29 '20 at 01:53
  • I interpreted this as something like `spread` from tidyverse, i.e. wanting to each column to represent the YIT data for a specific value of a key (the FARM variable). – stephematician Feb 29 '20 at 03:02
  • You may find these threads useful: https://stackoverflow.com/questions/60321045/cbind-with-loop-in-r and https://stackoverflow.com/questions/46058850/r-cbind-function-in-for-loop. Also https://stackoverflow.com/questions/48233811/r-cbinding-lists-of-data-tables which uses mapply instead of a loop. – MBorg Feb 29 '20 at 03:19

2 Answers2

0

If you really want to do this, it is possible:

df <- y1
for (i in 2:247) {
  df <- cbind(df, eval(parse(text=paste("y", i, sep = ''))))
}
Tianyi Shi
  • 883
  • 10
  • 15
0

Creating many variables in a loop as you do is not a good idea. You should use a list instead:

ys <- split(dairy$FARM, dairy$FARM)
names(ys) <- paste0("y", names(ys))

The first line creates list ys that contains your y1 as its first element (ys[[1]]), your y2 as its second element (ys[[2]]) and so on. The second line names the list elements the same way as you named your variables (y1, y2, etc.), since those will in the end be used to name the columns in the data frame.

There is a function in the dplyr package that takes a list of data frames and binds them all together as columns:

library(dplyr)
df <- bind_cols(ys)

Note, by the way, that this will only work, if each value appears exactly the same number of times in the column FARM, since the columns in a data frame must all have the same length.

Stibu
  • 15,166
  • 6
  • 57
  • 71