'Create R function from multiple scripts?

Not too good with functions. Is there a way to write the below script as a function? I have a list of dataframes that I want to apply the below scripts to.

head(iris)

iris1 <- iris %>% 
  group_by(Species) %>% 
      mutate_at(vars(Petal.Length), ~replace_na(., 0)) %>%
  summarise(Petal.Length = sum(Petal.Length))


iris2 <- iris %>% 
  group_by(Species) %>% 
  tally()

iris3 <- iris2 %>%
  inner_join(iris1)

iris3$average <- iris3$Petal.Length/iris3$n

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source