create multiple new dataframes by subsetting existing dataframe in a for loop

I have a data set that looks something like this

ID <- c("BOB", "BBP", "GCG", "GGO", "GOP", "ICO", "BGP")

df <- data.frame(

actor = sample(ID, size = 5, replace = TRUE),

target = sample(ID, size = 5, replace = TRUE),

power = runif(5)

)

I want to run a for loop that will go through the data frame and create a new data frame for every unique ID that pulls all the rows where that ID appears in either "actor" or "target". So essentially I have a data frame where every instance of BOB is subsetted.

I will have 60+ individuals, so making an individual data frame first and then filling it from a for loop would be a ton of time.

Is there a way I can make a for loop where a data frame is made for every unique 3 letter code that subsets all of its instances from a larger dataset?

One option is dplyr::group_split() but that that's experimental so we'll stay away.

Though others might have better answers, here's what I did:

library(tidyverse)
set.seed(1)
ID <- c("BOB", "BBP", "GCG", "GGO", "GOP", "ICO", "BGP")

df <- tibble(
  actor = sample(ID, size = 5, replace = TRUE),
  target = sample(ID, size = 5, replace = TRUE),
  power = runif(5)
) |>
  mutate(row_num = row_number(), .before = 1) # to ensure rows aren't duplicated later

df
#> # A tibble: 5 × 4
#>   row_num actor target power
#>     <int> <chr> <chr>  <dbl>
#> 1       1 BOB   GOP    0.206
#> 2       2 GGO   BGP    0.177
#> 3       3 BGP   GCG    0.687
#> 4       4 BOB   ICO    0.384
#> 5       5 BBP   BBP    0.770

combined <- bind_rows(
  df |> mutate(ID = actor),
  df |> mutate(ID = target)
) |> 
  distinct(ID, row_num, .keep_all = TRUE) |> # so each row is only present once per ID
  nest(.by = ID)

combined
#> # A tibble: 7 × 2
#>   ID    data            
#>   <chr> <list>          
#> 1 BOB   <tibble [2 × 4]>
#> 2 GGO   <tibble [1 × 4]>
#> 3 BGP   <tibble [2 × 4]>
#> 4 BBP   <tibble [1 × 4]>
#> 5 GOP   <tibble [1 × 4]>
#> 6 GCG   <tibble [1 × 4]>
#> 7 ICO   <tibble [1 × 4]>

combined |> 
  filter(ID == "BBP") |> 
  pull(data) |> 
  pluck(1)
#> # A tibble: 1 × 4
#>   row_num actor target power
#>     <int> <chr> <chr>  <dbl>
#> 1       5 BBP   BBP    0.770

Created on 2026-11-02 with reprex v2.1.1

try base R split(), works perfectly.