How to add ROW grantmakers / subtitles to Julia DataFrame?

Let's say I have a df similar to this one, where I have several categorical values ​​and several variables:

df = wsv"""
region product year prod cons
US     apples  2010 1    2
US     appels  2011 3    4
US     banana  2010 5    6
US     banana  2011 7    8
EU     apples  2010 9    10
EU     appels  2011 11   12
EU     banana  2010 13   14
EU     banana  2011 15   16
"""

How can I convert it to have totals / subtotals of the category as new lines i.e.

df2 = wsv"""
index  prod  cons
US     16    20
apples 4     6
2010   1     2
2011   3     4
banana 12    14
2010   5     6
2011   7     8
EU     48    52
apples 20    22
2010   9     10
2011   11    12
banana 28    30
2010   13    14
2011   15    16
"""

This is often useful after formatting correctly (for example, totals in bold ...) to report data, since many reports actually use this structure.

+1
source share
1 answer

You can use nested byto achieve something like this:

df2 = by(df, :region) do sub1
      t = DataFrame(product=NA, year=NA, prod=sum(sub1[:prod]), cons=sum(sub1[:cons]))
      sub1mod = by(sub1, [:region,:product]) do sub2
        t2 = DataFrame(year=NA, prod=sum(sub2[:prod]), cons=sum(sub2[:cons]))
        t3 = vcat(t2,sub2)
      end
      t2 = vcat(t,sub1mod)
end
delete!(df2,[:region_1,:region_2,:product_1])

Of:

14Γ—5 DataFrames.DataFrame
β”‚ Row β”‚ region β”‚ product  β”‚ year β”‚ prod β”‚ cons β”‚
β”œβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€
β”‚ 1   β”‚ "EU"   β”‚ NA       β”‚ NA   β”‚ 48   β”‚ 52   β”‚
β”‚ 2   β”‚ "EU"   β”‚ "apples" β”‚ NA   β”‚ 20   β”‚ 22   β”‚
β”‚ 3   β”‚ "EU"   β”‚ "apples" β”‚ 2010 β”‚ 9    β”‚ 10   β”‚
β”‚ 4   β”‚ "EU"   β”‚ "apples" β”‚ 2011 β”‚ 11   β”‚ 12   β”‚
β”‚ 5   β”‚ "EU"   β”‚ "banana" β”‚ NA   β”‚ 28   β”‚ 30   β”‚
β”‚ 6   β”‚ "EU"   β”‚ "banana" β”‚ 2010 β”‚ 13   β”‚ 14   β”‚
β”‚ 7   β”‚ "EU"   β”‚ "banana" β”‚ 2011 β”‚ 15   β”‚ 16   β”‚
β”‚ 8   β”‚ "US"   β”‚ NA       β”‚ NA   β”‚ 16   β”‚ 20   β”‚
β”‚ 9   β”‚ "US"   β”‚ "apples" β”‚ NA   β”‚ 4    β”‚ 6    β”‚
β”‚ 10  β”‚ "US"   β”‚ "apples" β”‚ 2010 β”‚ 1    β”‚ 2    β”‚
β”‚ 11  β”‚ "US"   β”‚ "apples" β”‚ 2011 β”‚ 3    β”‚ 4    β”‚
β”‚ 12  β”‚ "US"   β”‚ "banana" β”‚ NA   β”‚ 12   β”‚ 14   β”‚
β”‚ 13  β”‚ "US"   β”‚ "banana" β”‚ 2010 β”‚ 5    β”‚ 6    β”‚
β”‚ 14  β”‚ "US"   β”‚ "banana" β”‚ 2011 β”‚ 7    β”‚ 8    β”‚
+2
source

Source: https://habr.com/ru/post/1677283/


All Articles