data1=data.frame(Year=c(2010,2010,2010,2011,2011,2011,2010,2010,2010,2011,2011,2011),
Group=c(1,1,1,1,1,1,2,2,2,2,2,2),
Class=c('A','B','C','A','B','C','A','B','C','A','B','C'),
A=c(0.73,0.55,0.54,0.49,0.52,0.49,0.26,0.55,0.39,0.34,0.84,0.29),
B=c(0.12,0.08,0.14,0.21,0.33,0.98,0.33,0.99,0.02,0.59,0.27,0.72),
C=c(0.43,0.51,0.29,0.6,0.28,0.97,0.78,0.84,0.34,0.82,0.75,0.97))
##>data1
## Year Group Class A B C
## 1 2010 1 A 0.73 0.12 0.43
## 2 2010 1 B 0.55 0.08 0.51
## 3 2010 1 C 0.54 0.14 0.29
## 4 2011 1 A 0.49 0.21 0.60
## 5 2011 1 B 0.52 0.33 0.28
## 6 2011 1 C 0.49 0.98 0.97
## 7 2010 2 A 0.26 0.33 0.78
## 8 2010 2 B 0.55 0.99 0.84
## 9 2010 2 C 0.39 0.02 0.34
## 10 2011 2 A 0.34 0.59 0.82
## 11 2011 2 B 0.84 0.27 0.75
## 12 2011 2 C 0.29 0.72 0.97
I have 'data1' and wish to make 'data2'. 'data2' will have the same exact dimensions as 'data1' but I wish for the following conditions to be enacted,
IF Class = 'A', then Column 'B' = (1-B)*0.05, Column 'C' = (1-C)*0.05, and after updating Column 'B' and Column 'C', we calculate Column 'A' = 1- (B+C).
IF Class = 'B', then Column 'A' = (1-A)*0.05, Column 'C' = (1-C)*0.05, and after updating Column 'A' and Column 'C', we calculate Column 'B' = 1- (A+C).
IF Class = 'C', then Column 'A' = (1-A)*0.05, Column 'B' = (1-B)*0.05, and after > updating Column 'A' and Column 'B', we calculate Column 'C' = 1- (A+B).
I am hopeful for efficient data.table solution since I have very large dataset with many more 'Classes' than 3.
Here is a slow solution for making the hopeful updates.
library(data.table)
setDT(data1)
data1[, newB := fifelse(Class == 'A', (1-B) * 0.05, NA_real_)]
data1[, newC := fifelse(Class == 'A', (1-C) * 0.05, NA_real_)]
data1[, newA := fifelse(Class == 'A', (1-(newB+newC)), NA_real_)]
data1[, newA := fifelse(Class == 'B', (1-A) * 0.05, newA)]
data1[, newC := fifelse(Class == 'B', (1-C) * 0.05, newC)]
data1[, newB := fifelse(Class == 'B', (1-(newA+newC)), newB)]
data1[, newA := fifelse(Class == 'C', (1-A) * 0.05, newA)]
data1[, newB := fifelse(Class == 'C', (1-B) * 0.05, newB)]
data1[, newC := fifelse(Class == 'C', (1-(newA+newB)), newC)]