'Create filtered dataframe with dplyr and for loop
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.
Solution 1:[1]
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)
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | langtang |
| Solution 2 | Brenton M. Wiernik |
