如何将组合细胞封装为矢量

时间:2017-05-19 08:04:19

标签: r data.table

我有一个像

这样的数据表
library(data.table)
library(lifecontingencies)

dt <- data.table(cash = c(100,120), Flows = c(110,130),time = c(1,1), 
                 Ids = c(2,2), int = c(0.02,0.04), Rates = c(0.02,0.04),
                 proba = c(0.9,0.8), bilities = c(0.7,0.6))
dt

#   cash  Flows time Ids int  Rates proba bilities
#1: 100   110   1     2  0.02 0.02   0.9   0.7
#2: 120   130   1     2  0.04 0.04   0.8   0.6

并想要计算

#presentValue(cashFlows, timeIds, interestRates, probabilities) 

行方向。如何自动完成,而不是手动完成:

pV1 <- presentValue(cashFlows = c(100,110), 
                    timeIds = c(1,2), 
                    interestRates = c(0.02,0.02), 
                    probabilities = c(0.9,0.7))
pV2 <- presentValue(cashFlows = c(120,130), 
                    timeIds = c(1,2), 
                    interestRates = c(0.04,0.04), 
                    probabilities = c(0.8,0.6))
result <- c(pV1,pV2)
result
#162.2453 164.4231

3 个答案:

答案 0 :(得分:1)

当我们使用data.table时,一种方法是按行序列分组并应用函数

dt[, .(presValue = presentValue(cashFlows = unlist(c(cash, Flows)),
                  timeIds = unlist(c(time, Ids)), 
                  interestRates = unlist(c(int, Rates)), 
                  probabilities = unlist(c(proba, bilities)))), by = .(Row = 1:nrow(dt))]
#   Row presValue
#1:   1  162.2453
#2:   2  164.4231

另一种方法是通过melt将多个列合并为一个,然后应用presentValue

dM <- melt(dt, measure = patterns('cash|Flow', 'time|Ids', 'int|Rates', 'proba|bilities'),
        value.name = c('cashFlows', 'timeIds', 'interestRates', 'probabilities'))[,
           rn := rowid(variable)][]
dM[, .(presValue = do.call(presentValue, .SD)),
              by = .(Row = rn), .SDcols = cashFlows:probabilities]
#   Row presValue   
#1:   1  162.2453
#2:   2  164.4231

答案 1 :(得分:0)

我会通过apply

向您量化您的计算
apply(dt, 1, function(x) presentValue(cashFlows = x[1:2], 
                                               timeIds = x[3:4], 
                                               interestRates = x[5:6], 
                                               probabilities = x[7:8]))

# [1] 162.2453 164.4231

请注意,您可以按照自己的方式操作行的索引,例如,x[1:2]这里代表行的第一个和第二个单元格。您可以通过x[c(1,4)]选择第一个和第四个单元格,也可以通过x[2]

选择第二个单元格

答案 2 :(得分:0)

我花了一分钟来理解现在的价值以及它需要什么,但我认为这应该做你想要的。

apply(dt, 1, function(row) {
  cashFlows <- c(row[1], row[2])
  tIds <- c(row[3], row[4])
  interestRates <- c(row[5], row[6])
  probabilities <- c(row[7], row[8])
  presentValue(cashFlows = cashFlows,
               timeIds = tIds,
               interestRates = interestRates,
               probabilities = probabilities)
})