Suppose that I need to generate several new (sub-)dataframe by slicing an existing dataframe and assign a corresponding new name, for example:
carb1 <- mtcars[mtcars$carb == 1,]
carb2 <- mtcars[mtcars$carb == 2,]
carb3 <- mtcars[mtcars$carb == 3,]
carb4 <- mtcars[mtcars$carb == 4,]
...
I have tried:
library(purrr)
map2(paste0("carb",seq(1:4)),seq(1:4),~assign(.x,mtcars[mtcars$carb == .y,]))
It will generate a list of dataframe as I expected, but it does not assign the corresponding name to each new dataframe. The list of dataframe is totally ok for my use, but I would like to know a way to assign a name to each dataframe within one function (rather than assigning names to the list afterwards). Am I missing some hidden functions of map2
here?
Also, I am happy to know a way using the base R function to achieve what I want. Any ideas? Many thanks!