我有这个样本数据
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))
我从 Excel 中获取输入,其中单元格被命名为区域。 这些命名范围告诉您哪些列可用以及哪些列可以从
rawdata
使用
。
假设我正在尝试计算税后净额。我总是给出税率,但金额有时是税后金额,有时是总额。
因此,使用 ifelse 我需要创建一个税后列,如果给出的话,则在税后使用,否则计算它。反之亦然。
总列和净列均需提供,其中任何一个都给出。
这是我尝试过的代码。
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)];
D 列显示 E 列单元格的名称
输出应如下所示:
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))
问题并不完全清楚,但您似乎有一个现有的表(我在此图中仅包含
name
列):
# existing data
rawdata <- data.table(name = c("a", "b", "c", "d", "e"))
然后,您从 Excel 中读取一些向量,这些向量可能看起来像这样,其中存在一个或另一个税前/税后数字:
# vectors obtained from read.xlsx (conforming with the existing data)
taxrate <- c( 0.3, 0.2, 0.1, 0.05, 0.5)
beforetax <- c(2000, NA, 300, NA, 700)
aftertax <- c( NA, 160, NA, 570, NA)
解决方案是:
# put those vectors into the existing data.table
rawdata[, c("rate", "BeforeTax1", "AfterTax1") := data.table(taxrate, beforetax, aftertax)]
# replace the missing values with a calculation
rawdata[is.na(BeforeTax1), BeforeTax1 := AfterTax1 / (1-rate)]
rawdata[is.na(AfterTax1), AfterTax1 := BeforeTax1 * (1-rate)]
结果:
> rawdata
name rate BeforeTax1 AfterTax1
<char> <num> <num> <num>
1: a 0.30 2000 1400
2: b 0.20 200 160
3: c 0.10 300 270
4: d 0.05 600 570
5: e 0.50 700 350