How to write loops for loops in R using dplyr syntax

I have an extensive block of code that I wrote using the dplyr syntax in R. However, I am trying to put this code in a loop to end up creating multiple output files, not just one. Unfortunately, I cannot do this.

To illustrate my problem, let me refer to the commonly used "iris" dataset in R:

      > data("iris")
      > str(iris)
      'data.frame': 150 obs. of  5 variables:
      $ Sepal.Length: num  
      $ Sepal.Width : num  
      $ Petal.Length: num  
      $ Petal.Width : num  
      $ Species     : Factor w/ 3 levels "setosa","versicolor","virginica"

Say I want to keep the middle petal. The length of the species is versicolor. The dplyr code might look like this:

    MeanLength2 <- iris %>% filter(Species=="versicolor")
                       %>% summarize(mean(Petal.Length)) %>% print()

Which will give the following value:

      mean(Petal.Length)
    1               4.26

Let's try to create a loop to get the average length of the petals for all species.

From the fact that I know little about loops, I would like to do something like this:

     for (i in unique(iris$Species))
      {
       iris %>% filter(iris$Species==unique(iris$Species)[i]) %>%
        summarize(mean(iris$Petal.Length)) %>% print()
        print(i) 
       }

- , dplyr. , .

:

          mean(iris$Petal.Length)
     1                   3.758
     [1] "setosa"
          mean(iris$Petal.Length)
     1                   3.758
     [1] "versicolor"
          mean(iris$Petal.Length)
     1                   3.758
     [1] "virginica"  

, 3.758 , . , "" . , , , , , .

- ? , , , , , "group_by" dplyr, 100 PDF , , , , .

+4
2

, , , group_by, split() :

iris %>% 
  group_by(Species) %>% 
  summarise(mn = mean(Petal.Length)) %>% 
  split(.,.$Species)

$setosa
# A tibble: 1 × 2
  Species    mn
   <fctr> <dbl>
1  setosa 1.462

$versicolor
# A tibble: 1 × 2
     Species    mn
      <fctr> <dbl>
1 versicolor  4.26

$virginica
# A tibble: 1 × 2
    Species    mn
     <fctr> <dbl>
1 virginica 5.552
+5

, . , , . , i "setosa":

> iris  %>% filter(iris$Species == unique(iris$Species)["setosa"])
[1] Sepal.Length Sepal.Width  Petal.Length Petal.Width  Species     
<0 rows> (or 0-length row.names)

- , , :

> iris  %>% filter(iris$Species == unique(iris$Species)["setosa"]) %>%  
+ summarize(mean(iris$Petal.Length))
  mean(iris$Petal.Length)
1                   3.758

, iris , :

> filter(iris, iris$Species == unique(iris$Species)["setosa"]) %>% 
+ summarize(mean(mtcars$cyl))
  mean(mtcars$cyl)
1           6.1875

, , , .

TJ Mahr, :

> for (i in unique(iris$Species))
+ {
+     iris %>% filter(Species==i) %>%
+         summarize(mean(Petal.Length)) %>% print()
+     print(i) 
+ }
  mean(Petal.Length)
1              1.462
[1] "setosa"
  mean(Petal.Length)
1               4.26
[1] "versicolor"
  mean(Petal.Length)
1              5.552
[1] "virginica"

,

+3

Source: https://habr.com/ru/post/1653372/


All Articles