I have this sample data
rawdata <- data.table( name = c("a", "b", "c", "d", "e"), btax = c(2000, 200, 300, 600, 700), rate = c(0.3, 0.2, 0.1, 0.05, 0.5))
I am taking input from excel where the cells are named region.
these named ranges tells which columns are available and which ones to use from the rawdata
.
Let say I am trying to calculate net figure after tax. I have the tax rate always given but the amount is some times after tax and some times in gross.
so using an ifelse I need to create a column after tax which is use after tax if it is given else calculate it. and vice verse.
both gross and net columns are required with either of them given.
This is the code which I have tried.
beforetax<-read.xlsx(xlsxFile="//xxxxxxxx/Book1.xlsx",namedRegion="beforetax", colNames=FALSE)[,1];
aftertax<-read.xlsx(xlsxFile="//xxxxxxxxx/Book1.xlsx",namedRegion="aftertax", colNames=FALSE)[,1];
taxrate<-read.xlsx(xlsxFile="//xxxxxxxxx/Book1.xlsx",namedRegion="taxrate", colNames=FALSE)[,1];
rawdata[, net := get(beforetax)*get(rate)];
rawdata[, net := get(aftertax)];
column D shows the name of the cell of column E
Output should look like this:
data.table( name = c("a", "b", "c", "d", "e"), btax = c(2000, 200, 300, 600, 700), rate = c(0.3, 0.2, 0.1, 0.05, 0.5), BeforeTax1 = c(2000, 200, 300, 600, 700), AfterTax1 = c(1400, 160, 270, 570, 350))

[Rewritten now that I think I understand the problem]
Reproducible example:
Solution (
data.table< V1.15.0):Result:
Alternative solution (
data.table>= V1.15.0) avoidinggetwhich is now discouraged in favour ofenv(and also using theletalias for':='):See this vignette on Programming with data.table as mentioned by @SamR