I have this dataframe:
df<-data.frame(a=c("a1","a2","a3","a4","b1","b2","b3","b4","a1","a2","a3","a4","b1","b2","b3","b4"), b=c("x1","x2","x3","total","x1","x2","x3","total", "x1","x2","x3","total","x1","x2","x3","total"), reg=c("A","A","A","A","A","A","A","A","B", "B","B","B","B","B","B","B"), c=c(1:16))
which looks like:
a b reg c
1 a1 x1 A 1
2 a2 x2 A 2
3 a3 x3 A 3
4 a4 total A 4
5 b1 x1 A 5
6 b2 x2 A 6
7 b3 x3 A 7
8 b4 total A 8
9 a1 x1 B 9
10 a2 x2 B 10
11 a3 x3 B 11
12 a4 total B 12
13 b1 x1 B 13
14 b2 x2 B 14
15 b3 x3 B 15
16 b4 total B 16
columns 'a', 'b' and 'reg' are categorical variables. What I want to do is to create a new column which divides x(i), where i=1,2,3 with 'total' (x(i)/total) for each category in reg' and in
a' columns.
Can someone help me with this ?
Assuming your df is ordered like your example .
Base on Op's explanation ,Below are working for the real data of he/she.(From OP)
Just using R base:
Output: