[SOLVED] Create R function from multiple scripts?

Issue

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

Solution

Yes, its quite easy.

Let me know if this helps you:

my_function_name <- function(df){

table1 <- df %>%
  group_by(org) %>%
  tally()
table2 <- df %>%
  group_by(org) %>%
  mutate_at(vars(hours), ~replace_na(., 0)) %>%
  summarise(hours = sum(hours))

table3 <- table1 %>%
  inner_join(table2)

table3$average <- table3$hours/table3$n

return(list(table1,table2,table3))

}

# Calling the function
results <- my_function_name(df)
results$table1
results$table2
results$table3

In this case I used the function to retrieve all the tables. If you only want the final number table3$hours/table3$n what we can do is change the return of the function:

my_function_name <- function(df){

table1 <- df %>%
  group_by(org) %>%
  tally()
table2 <- df %>%
  group_by(org) %>%
  mutate_at(vars(hours), ~replace_na(., 0)) %>%
  summarise(hours = sum(hours))

table3 <- table1 %>%
  inner_join(table2)

table3$average <- table3$hours/table3$n

return(table3$average)

}

# Calling the function
results <- my_function_name(df)
results

Answered By – AugtPelle

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *