How to assign values to a data table from a second table if both first row and and column values match

Viewed 43

I have two data.tables similar to tables below. I want to find the values from the first table if the values of first column and column names between two tables match and assign it to the second table.

I tried to generate similar examples using mtcars dataset

mtcars_first <- add_column(mtcars, car = rownames(mtcars), .before =  1)


mtcars_second <- rbind(
                   c("Hornet 4 Drive",NA,NA,NA),
                   c("Valiant",NA,NA,NA),
                   c("Duster 360" ,NA,NA,NA)) %>% as.data.table()

colnames(mtcars_second) <- c("car","disp","drat","qsec")

1 Answers
mtcars_second[mtcars_first, c("disp","drat","qsec") := .(i.disp, i.drat, i.qsec), on=.(car)]
mtcars_second
#               car   disp   drat   qsec
#            <char> <char> <char> <char>
# 1: Hornet 4 Drive    258   3.08  19.44
# 2:        Valiant    225   2.76  20.22
# 3:     Duster 360    360   3.21  15.84
Related