I want to create several data frames from an original one in R using for
loop.
I want to get three separated data frames for each species to conduct separate analysis.
I tried the following code but it doesn't work:
data(iris)
library(dplyr)
for i in levels(iris$Species){
paste0(i,".data") <- data.frame(filter(iris,
Species=="i"))
}
I do not necessarily need dplyr but it's the one I am used to.
CodePudding user response:
I think it is better to keep the separate frames in a list, which as pointed out in the comments is done easily with split(iris, iris$Species)
If you really want them out of the list and into separate named frames, you can use
list2env(split(iris, iris$Species),envir = .GlobalEnv)
CodePudding user response:
An even better approach would be to keep everything in one data frame and then use dplyr/tidyr’s group_by()
and nest()
functions to fit a model for each group.
See here for a detailed walkthrough: https://tidyr.tidyverse.org/articles/nest.html