下面是使用data.table
結合一種可能的方法與zoo
library(data.table) ; library(zoo) # loading the packages
setkey(setDT(TABLE1), V2) # converting to `data.table` object and setting a key for a binary join
TABLE1[TABLE2, MATCH := i.V1] # conducting binary join (I'm assuming the column in TABLE2 called "V1") and updating MATCH by reference
setorder(TABLE1, INDEX, na.last = TRUE) # reordering back by INDEX
TABLE1[, MATCH := na.locf(MATCH)] # filling the NAs with the previous value in MATCH
# V1 V2 INDEX MATCH
# 1: U 30 1 30
# 2: V 3 2 30
# 3: V 25 3 30
# 4: V 4 4 30
# 5: NA 5 30
# 6: U 54 6 54
# 7: V 9 7 54
# 8: V 22 8 54
# 9: V 90 9 54
# 10: NA 10 54
# 11: U 61 11 61
DATA
TABLE1 <- structure(list(V1 = structure(c(2L, 3L, 3L, 3L, 1L, 2L, 3L, 3L,
3L, 1L, 2L), .Label = c("", "U", "V"), class = "factor"), V2 = c(30L,
3L, 25L, 4L, NA, 54L, 9L, 22L, 90L, NA, 61L), INDEX = 1:11), .Names = c("V1",
"V2", "INDEX"), class = "data.frame", row.names = c(NA, -11L))
TABLE2 <- structure(list(V1 = c(30L, 54L, 61L, 6L)), .Names = "V1", class = "data.frame", row.names = c(NA,
-4L))
謝謝你的快速反應和評論。這是我正在尋找的。但是我仍然沒有得到正確的結果,我得到了比賽,但是在空白行之前的所有條目都不相同。 – jlroo
我已經提供了我使用的數據集,請參閱我的編輯。 –
這工作,非常感謝你。我在將data.frame更改爲data.table時遇到了問題。 – jlroo