Binding dataframes by multiple conditions in R -
i have data frame looks this:
> data class number 1 1 2 2 3 3 4 b 1 5 b 2 6 b 3 7 c 1 8 c 2 9 c 3 i have reference data frame is:
> reference class number value 1 1 0.5 2 b 3 0.3 i want join these data frames create single data frame:
> resultdata class number value 1 1 0.5 2 2 0.0 3 3 0.0 4 b 1 0.0 5 b 2 0.0 6 b 3 0.3 7 c 1 0.0 8 c 2 0.0 9 c 3 0.0 how can achieve this? appreciated
you can do
library(data.table) setkey(setdt(reference), class, number)[data] or
setkey(setdt(data), class, number)[reference, value:= i.value][is.na(value), value:=0] # class number value #1: 1 0.5 #2: 2 0.0 #3: 3 0.0 #4: b 1 0.0 #5: b 2 0.0 #6: b 3 0.3 #7: c 1 0.0 #8: c 2 0.0 #9: c 3 0.0
Comments
Post a Comment