How to create a function to condense code?

Context: I am wondering how to create a function to optimise this code?

df_word2 <- df_word2 %>% mutate(VA_prod=(repet*VA_mean_sum)) # prep: product of repeats * mean V+A ratings
  sumVAprod_word <- aggregate(df_word2[, 8], list(df_word2$year), sum) %>% rename(c("year"="Group.1", "sumVAprod_word"="x"))  # sum VA_prod by year
  df_word2 <- df_word2 %>% mutate(A_prod=(repet*A_mean_sum)) # prep: product of repeats * mean A ratings
  sumAprod_word <- aggregate(df_word2[, 9], list(df_word2$year), sum) %>% rename(c("year"="Group.1", "sumAprod_word"="x")) # sum A_prod by year
  df_word2 <- df_word2 %>% mutate(V_prod=(repet*V_mean_sum_r)) # prep: product of repeats * mean V ratings 
  sumVprod_word <- aggregate(df_word2[, 10], list(df_word2$year), sum) %>% rename(c("year"="Group.1", "sumVprod_word"="x"))# sum V_prod by year

data frame:

what if any parts would be parametrised ?
It does look somewhat odd to mix dplyr mutates, but favour aggregate over dplyr group_by/summarise, so I'd probably start there.

final note, pasting an image of a data.frame while giving 'some idea' of what you are working with, doesnt do much to help forum users to help you, rather it would seem to demand of them to do more work to get your existing code up and running. Are they expected to type out the contents of the data.frame ?
There are tools for communicating data.frames (or samples thereof) to the forum. base::dput() and datapasta package functions for example.
Here is the guide.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.