data.table优化 - 条件求和

时间:2018-03-10 15:53:33

标签: r optimization data.table

我正在尝试对data.table进行条件求和,并设法以杂乱的方式进行。我想知道是否可以更优雅地做到这一点?

请考虑以下事项:

library(data.table)
stock_profile <- data.table(Pcode = c(123456L, 234567L, 345678L, 456789L, 567891L, 678912L, 789123L, 891234L, 912345L, 123456L, 234567L, 345678L, 456789L, 567891L, 678912L, 789123L, 891234L, 912345L), 
    Value = c(51.96, 89.64, 21.56, 56.04, 47.56,83.68, 42.21, 66.56, 62.72, 35.00, 3.40, 30.82, 59.83, 82.17, 14.02, 25.70, 81.38, 50.33), 
    Location = c("A", "A", "A", "A", "A", "A", "A", "A", "A","B", "B", "B", "B", "B", "B", "B", "B", "B"), 
    NoSales = c("","", "Y", "", "", "Y", "", "", "Y", "", "", "Y", "Y", "","", "", "Y", "Y"))

哪个应该导致以下结果:

Pcode   Value   Location    NoSales
123456  51.96   A   
234567  89.64   A   
345678  21.56   A           Y
456789  56.04   A   
567891  47.56   A   
678912  83.68   A           Y
789123  42.21   A   
891234  66.56   A   
912345  62.72   A           Y
123456  35      B   
234567  3.4     B   
345678  30.82   B           Y
456789  59.83   B           Y
567891  82.17   B   
678912  14.02   B   
789123  25.7    B   
891234  81.38   B           Y
912345  50.33   B           Y

我要做的是将库存从位置B转移到A,并找出没有销售的库存总价值。所以我需要在位置A的NoSales中带有标志Y的所有产品的价值总和,以及位置B中位置A中没有销售标志Y的所有产品的价值。

到目前为止,我已经完成了以下工作:

# get all NoSales flag Y products in Location A
ANoSales <- stock_profile[Location == "A" & NoSales == "Y"]    
# get all prodcuts in location B 
BStock <- stock_profile[Location == "B"]
# left merge 
NoSalesAll <- merge(ANoSales,BStock,by="Pcode",all.x = TRUE)
# create new column aggregating the value and give the total sum
NoSalesAll[,Value := Value.x + Value.y][,sum(Value)]

它有效,但不是很优雅。我认为ifelse应该可以吗?欢迎并赞赏任何建议:)

3 个答案:

答案 0 :(得分:5)

我不确定这是多么优雅,但在这里,

library(data.table)

sum(
  rowSums(dcast(stock_profile, Pcode ~ Location + NoSales, value.var = 'Value')
            [!is.na(A_Y), -1], na.rm = TRUE)
  )
#[1] 263.13

根据@ Frank的评论,我们可以使用rowSums来避免.SD

dcast(dt, Pcode ~ Location + NoSales, value.var = 'Value')[
  !is.na(A_Y), sum(.SD, na.rm=TRUE), .SDcols=-1]

答案 1 :(得分:2)

我喜欢Sotos answer。 但如果你定义&#34;优雅&#34;作为data.table以外的其他方法,与dplyr的方法相比:

stock_profile %>% 
  filter(Location=="A" & NoSales=="Y") %>% 
  left_join(filter(stock_profile, Location=="B"), by="Pcode") %>% 
  mutate(value=Value.x+Value.y) %>% 
  summarise_at(vars(value),sum)

输出

   value
1 263.13

答案 2 :(得分:1)

这是我的贡献。

setkey(stock_profile, Location, NoSales)
DT1 = stock_profile[.("A","Y"), sum(Value),by=.(Pcode)]
DT2 = stock_profile[.("B"), sum(Value),by=.(Pcode)]
DT = merge(DT1, DT2, by="Pcode", all.x=TRUE)
DT[, .SD, .SDcols = names(DT) %like% "V1.x|V1.y"][,sum(V1.x,V1.y)]