如何基于2个聚合列从R中的另一列中减去1列
我希望输出为'total_data'列名:'LocationID','PartNumber','Quantity_subtract',其中 数量\u减去=总计\u进\u进\u出$Quantity-总计\u出\u出$Quantity,按每个“LocationID”和“PartNumber”分组 我试过这个:-如何基于2个聚合列从R中的另一列中减去1列,r,database,dataframe,data-manipulation,R,Database,Dataframe,Data Manipulation,我希望输出为'total_data'列名:'LocationID','PartNumber','Quantity_subtract',其中 数量\u减去=总计\u进\u进\u出$Quantity-总计\u出\u出$Quantity,按每个“LocationID”和“PartNumber”分组 我试过这个:- matchingCols <- c('LocationID','PartNumber') mergingCols <- names(coming_in)[3] total_com
matchingCols <- c('LocationID','PartNumber')
mergingCols <- names(coming_in)[3]
total_coming_in[total_going_out,on=matchingCols,
lapply(
setNames(mergingCols),
function(x) get(x) - get(paste0("i.", x))
),
nomatch=0L,
by=.EACHI
]
matchingCols所以您希望有一个列,为PartNumber
和LocationID
的每个组合提供total\u coming\u in
和total\u coming\u out
的差异,对吗
如果是,请执行以下操作:
library(dplyr)
matchingCols <- c("LocationID", "PartNumber")
total_data <- full_join(total_coming_in, total_going_out, by=matchingCols)
total_data <- mutate(total_data, Quantity_subtract = Quantity.x - Quantity.y)
total_data <- select(total_data, -Quantity.x, -Quantity.y) #if you want to get rid of these columns
库(dplyr)
匹配COLS所以您希望有一个列,为您提供零件号
和位置ID
的每种组合的总进出量
,对吗
如果是,请执行以下操作:
library(dplyr)
matchingCols <- c("LocationID", "PartNumber")
total_data <- full_join(total_coming_in, total_going_out, by=matchingCols)
total_data <- mutate(total_data, Quantity_subtract = Quantity.x - Quantity.y)
total_data <- select(total_data, -Quantity.x, -Quantity.y) #if you want to get rid of these columns
库(dplyr)
使用data.table
匹配cols正如您所希望的那样,我会首先将两个表干净地合并,然后仅对有意义的行执行减法运算(即,对于total\u coming\u in
中的行,它们在total\u going\u out
中具有匹配值,反之亦然):
如您所愿,使用data.table
,我将首先干净地合并两个表,然后仅对有意义的行执行减法操作(即,对于total\u coming\u in
中的行,它们在total\u going\u out
中具有匹配值,反之亦然):
library(data.table)
M <- merge(total_coming_in, total_going_out, by = c('LocationID','PartNumber'))
# i.e. all.x = FALSE, all.y = FALSE,
# thereby eliminating rows in x without matching row in y and vice-versa
M[ , Quantity_subtract := Quantity.x - Quantity.y,
by = c('LocationID','PartNumber')]
M <- merge(total_coming_in, total_going_out, all = TRUE, by = c('LocationID','PartNumber'))
# i.e. all.x = TRUE, all.y = TRUE,
# thereby allowing rows in x without matching row in y and vice-versa
M[is.na(Quantity.x), Quantity.x := 0]
M[is.na(Quantity.y), Quantity.y := 0]
M[ , Quantity_subtract := Quantity.x - Quantity.y,
by = c('LocationID','PartNumber')]