I have a data frame like this:
Group Col A Col B
1 A1 B1
1 A2 B2
2 A3 B3
2 A4 B4
I want to create a new columns Per A and Per B respecting grouops, so the outcome should be
Group Col A Col B Per A Per B
1 A1 B1 100*A1/(A1+A2) 100*B1/(B1+B2)
1 A2 B2 100*A2/(A1+A2) 100*B2/(B1+B2)
2 A3 B3 100*A3/(A3+A4) 100*B3/(B3+B4)
2 A4 B4 100*A4/(A3+A4) 100*B4/(B3+B4)
I need a general case, with several groups each of which having different group sizes.
I tried using a for loop, and while I am able to find the columns, I cannot assign them to the data frame. I don't understand what is exactly that prevents it.
For example, this is a result I'd be looking for (note how I change the Group column reflecting "different group sizes")
Group Col A Col B Per A Per B
1 1 2 100.0 100.0
2 1 2 16.67 25.00
2 2 2 33.33 25.00
2 3 4 50.00 50.00