0

I've been trying to search for a way to write a for loop to create subsets from my dataset, based on the variable plot number (plot_no).

I could do in manually like this. However, there are 30 plots so I rather write a for loop. l_plot1 <- light[light$Plot_No == 1,] l_plot2 <- light[light$Plot_No == 2,] l_plot3 <- light[light$Plot_No == 3,]

I have tried this:

all_plots <- unique(light$Plot_No)

n <- length(all_plots)

for(i in 1:n){plot_i <- all_plots[i]  

 plot_i <- light[light$Plot_No == i,]    

 }

But then the for loop keeps overwriting the data frame and I end up with only a data frame of the last plot.

How do I write it so that all 30 dataframes will save and are filled with data from the light data frame?

user438383
  • 5,716
  • 8
  • 28
  • 43
Kiki_Bo
  • 1
  • 1
  • 1
    Take a look at ?split – Dason Apr 10 '23 at 14:49
  • 3
    Like [this](https://stackoverflow.com/questions/49560584/how-to-create-multiple-subsets-of-data-based-on-a-column-name-without-specifying#comment86129212_49560584)? This question is almost surely a duplicate. – Rui Barradas Apr 10 '23 at 14:54
  • 1
    I added a couple more duplicate links. You can make a `list` of subt data frames with `my_list = split(all_plots, all_plots$Plot_No)`. I'd recommend keeping the sub data frames in a `list` rather than separate objects (see my answer at [How to make a list of data frames?](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) for explanation and examples. But I'd also suggest that in most cases you don't need to do this splitting at all... if you use `dplyr` or `data.table` it's easier to do things to a grouped data frame than to a bunch of separate data frames. – Gregor Thomas Apr 10 '23 at 15:04

0 Answers0