I have this dataset -
print(df) object group 1 apple A 1 banana B 1 pear A 1 robot C print(df2) object group
We can do this in data.table
data.table
library(data.table) reference <- setDT(df2)[df, .N, on = .(object), by = .EACHI]$N df$reference <- reference df # object group reference #1: apple A 3 #2: banana B 1 #3: pear A 0 #4: robot C 3