Search code examples
rdataframeaggregatepercentage

Aggregate a dataframe in R and take column wise proportion


I have a dataframe like this:

Year Net Cost Gross
2010 5637 6749 6849
2011 5738 2810 5749
2012 4829 5738 5783
2013 9587 6749 5739
2014 4638 6739 6748

I want column wise percerntages for each year:

Year Net Cost Gross
2010 XX% XX% XX%
2011 XX% XX% XX%
2012 XX% XX% XX%
2013 XX% XX% XX%
2014 XX% XX% XX%

These percentages are column wise percentages. I coded as this:

percent = prop.table(as.matrix(test[2:4]), margin=2)

But I do not get the Year column. Please help!


Solution

  • We could use mutate with across

    library(dplyr)
    test %>%
         mutate(round(100 *across(2:4, proportions), 2))
    

    -output

      Year   Net  Cost Gross
    1 2010 18.53 23.45 22.19
    2 2011 18.86  9.76 18.62
    3 2012 15.87 19.93 18.73
    4 2013 31.51 23.45 18.59
    5 2014 15.24 23.41 21.86
    

    With the OP's code, we could cbind with the first column

    cbind(test[1], prop.table(as.matrix(test[2:4]), margin=2))
    

    data

    test <- structure(list(Year = 2010:2014, Net = c(5637L, 5738L, 4829L, 
    9587L, 4638L), Cost = c(6749L, 2810L, 5738L, 6749L, 6739L), Gross = c(6849L, 
    5749L, 5783L, 5739L, 6748L)), class = "data.frame", row.names = c(NA, 
    -5L))