Split a dataframe into multiple df and split value as the df name

I have a dataframe like the following one :

dom_output <- data.frame(
  Site = c("alpha", "beta", "charlie", "delta","alpha", "beta", "charlie", "delta"),
  Value = c(11,22,33,44,55,66,77,88),
  label  = c("Watermelon","Vanilla","Default","Default","Watermelon","Vanilla","Default","Default")

I want to split it different data frames based on Site . So the new data frame names should be based of the Site. I know how to filter and select it but how do I do it in a loop and name the df based on the split value itself.

So I would have 4 df alpha,beta,charlie, delta.

Simply use list2env:

#> character(0)

dom_output <- data.frame(Site = c("alpha", "beta", "charlie", "delta","alpha", "beta", "charlie", "delta"),
                         Value = c(11,22,33,44,55,66,77,88),
                         label  = c("Watermelon","Vanilla","Default","Default","Watermelon","Vanilla","Default","Default"))

#> [1] "dom_output"

list2env(x = split(x = dom_output,
                   f = dom_output$Site),
         envir = globalenv())
#> <environment: R_GlobalEnv>

#> [1] "alpha"      "beta"       "charlie"    "delta"      "dom_output"

Created on 2019-09-19 by the reprex package (v0.3.0)

Just to let you know, I have been recommended against using it earlier on SO.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.