你可以做data.table聯接。
library(data.table)
## set both data frames to data tables
setDT(Data1); setDT(Data2)
## copy 'Data2' to a new table 'Output' which we will assign values to
Output <- copy(Data2)
## join on 'ID' and assign by reference the relevant 'frequency' values
Output[Data1, frequency := i.frequency, on = "ID"]
Output
# ID frequency
# 1: 1 1
# 2: 2 7
# 3: 3 11
# 4: 4 0
# 5: 5 4
# 6: 6 0
原始數據:
Data1 <- structure(list(ID = c(1L, 2L, 3L, 5L), frequency = c(1L, 7L,
11L, 4L)), .Names = c("ID", "frequency"), class = "data.frame", row.names = c(NA,
-4L))
Data2 <- structure(list(ID = 1:6, frequency = c(0L, 0L, 0L, 0L, 0L, 0L
)), .Names = c("ID", "frequency"), class = "data.frame", row.names = c(NA,
-6L))
我會用'DATA2 [匹配(數據1 $ ID,DATA2 $ ID), '頻率'] < - 數據1 $ frequency' –
沿着正確的線,但是這將取代'DATA2'中的值,而不是創建一個新的'Output'。 – neilfws
DATA2總是隻包含零,還是可以包含其他值,您可能不想替換? – neilfws