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.