i have extensive block of code i've written using dplyr syntax in r. however, trying put code in loop, can create multiple output files opposed one. unfortunately, appear unable so.
for illustration purposes regarding problem, let's refer 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"
let's want save average petal.length of species "versicolor". dplyr code following:
meanlength2 <- iris %>% filter(species=="versicolor") %>% summarize(mean(petal.length)) %>% print()
which give following value:
mean(petal.length) 1 4.26
lets attempt create loop average petal length of species.
from little know of loops, want this:
(i in unique(iris$species)) { iris %>% filter(iris$species==unique(iris$species)[i]) %>% summarize(mean(iris$petal.length)) %>% print() print(i) }
for reason, had specify data frame , column inside loop, not case while using piping functionality of dplyr. i'm assuming indicative of problem.
anyways, above code gives following output:
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"
so code outputting 3.758 3 times, average petal length across species in dataset. indicates "filter" code did not work expected. can tell, appears loop functioned intended, 3 unique species names printed in eventual output.
how can 1 go doing use of loops? understand particular exercise not require use of fancy loops 1 can average petal length of species using, example, "group_by" function in dplyr, looking output close 100 unique table , pdf files dataset working , knowing how use loops purpose.
as mentioned in comment, if need results separated, easier use group_by
, split()
results:
iris %>% group_by(species) %>% summarise(mn = mean(petal.length)) %>% split(.,.$species) $setosa # tibble: 1 × 2 species mn <fctr> <dbl> 1 setosa 1.462 $versicolor # tibble: 1 × 2 species mn <fctr> <dbl> 1 versicolor 4.26 $virginica # tibble: 1 × 2 species mn <fctr> <dbl> 1 virginica 5.552
Comments
Post a Comment