0

I have this function:

my_fun <- function(x) { 
  x %>%       
    separate_rows(tags, sep=',\\s*') %>%
    separate(tags, c('tags', 'Value'), sep='\\s*-\\s*', fill='right') %>%
    mutate(tags=trimws(tags)) %>% 
    count(Year, tags) %>%
    pivot_wider(names_from=tags, values_from=n, values_fill=0) %>%
    adorn_totals("row") 
}

Is it possible to add these two lines to the function, after "adorn_totals"? The first one orders the columns by the last row value (minus the first one), and the second sums all rows (minus the first one) and adds it as a new column

[c(1, order(-[nrow(), -1]) + 1)]
rowSums([, -1])
jay.sf
  • 60,139
  • 8
  • 53
  • 110
J.Doe
  • 165
  • 7
  • 1
    it's possible, but does not make much sense. You dataframe df2 is declared outside of the function. So you are creating a dependence – mischva11 Jan 26 '22 at 09:32
  • thanks for pointing that out. I edited it to make it make more sense hopefully? – J.Doe Jan 26 '22 at 09:36
  • 1
    Would it be possible to share some example data to test this function? For the first part of your question, I would try to use the `relocate()` dplyr function which relocates the columns. For the second part of your question, you might want to look at this answer: https://stackoverflow.com/a/64595719/10740287 – DoRemy95 Jan 26 '22 at 09:41
  • Thank you. Your link answered the second part of my question with rowwise() %>% mutate(sumrange = sum(c_across(2:15), na.rm = T)) – J.Doe Jan 26 '22 at 12:56

0 Answers0