[英]Can someone explain how mult works in data.table when it performs update in joins (using .EACHI and mult)
我再次努力理解執行更新時加入時mult
參數是如何工作的。 我想要做的是實現lj 中定義的左連接。
出於性能原因,我想更新左表
“不平凡”的部分是,當左表和右表有一個共同的列時,(不考慮連接列),我想使用右表中的第一個值來覆蓋左表。 我認為mult
會幫助我處理這個多重匹配問題,但我做對了
library(data.table)
X <- data.table(x = c("a", "a", "b", "c", "d"), y = c(0, 1, 1, 2, 2), t = 0:4)
X
# x y t
# <char> <num> <int>
#1: a 0 0
#2: a 1 1
#3: b 1 2
#4: c 2 3
#5: d 2 4
Y <- data.table(xx = c("f", "b", "c", "c", "e", "a"), y = c(2, NA, 3, 4, 5, 6), u = 2:7)
Y
# xx y u
# <char> <num> <int>
#1: f 2 2
#2: b NA 3
#3: c 3 4
#4: c 4 5
#5: e 5 6
#6: a 6 7
# Expected result
# x y t
# <char> <num> <int>
#1: a 6 0 <= single match on xx == "a" so Y[xx == "a", y] is used
#2: a 6 1 <= single match on xx == "a" so Y[xx == "a", y] is used
#3: b NA 2 <= single match on xx == "b" so Y[xx == "b", y] is used
#4: c 3 3 <= mult match on xx == "c" so Y[xx == "c", y[1L]] is used
#5: d 2 4 <= no xx == "d" in Y so nothing changes
copy(X)[Y, y := i.y, by = .EACHI, on = c(x = "xx"), mult = "first"][]
# x y t
# <char> <num> <int>
#1: a 6 0
#2: a 1 1 <= a should always have the same value ie 6
#3: b NA 2
#4: c 4 3 <= y == 4 is not the first value of y in the Y table
#5: d 2 4
# Using mult = "all" is the closest I get from the right result
copy(X)[Y, y := i.y, by = .EACHI, on = c(x = "xx"), mult = "all"][]
# x y t
# <char> <num> <int>
#1: a 6 0
#2: a 6 1
#3: b NA 2
#4: c 4 3 <= y == 4 is not the first value of y in the Y table
#5: d 2 4
有人可以向我解釋上面有什么問題嗎?
我想我可以使用Y[X, ...]
來達到我想要的效果,問題是 X 非常大,使用Y[X, ...]
我得到的性能要差得多
我想使用右表中的第一個值來覆蓋左表的值
選擇第一個值並單獨更新它們:
X[unique(Y, by="xx", fromLast=FALSE), on=.(x=xx), y := i.y]
x y t
1: a 6 0
2: a 6 1
3: b NA 2
4: c 3 3
5: d 2 4
fromLast=
可以在刪除欺騙時選擇第一行或最后一行。
如何處理多個匹配項:
在x[i, mult=]
,如果i
的一行有多個匹配,則mult
確定x
哪些匹配行被選中。 這解釋了 OP 中顯示的結果。
在x[i, v := iv]
如果多行i
匹配到同一行中的x
,所有相關的i行的寫入X列順序,所以最后的i-行得到最終寫入。 打開詳細輸出以查看更新中進行了多少編輯——在這種情況下它將超過 x 行數(因為這些行被重復編輯):
options(datatable.verbose=TRUE)
data.table(a=1,b=2)[.(a=1, b=3:4), on=.(a), b := i.b][]
# Assigning to 2 row subset of 1 rows
a b
1: 1 4
如果在 join with 時更新,mult 總是等於“last”:=
我記得它在文檔中的某處有所描述。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.