1

I have two data.table objects in R: library(data.table)

spp <- c('A','B','C','D','E')
state <- c('Z','Q',NA,'Z','Q')
d1 <- data.table(spp,state)

spp <- c('C','B','K')
state <-c('Z','Q','Q')
d2 <- data.table(spp,state)

The observation C in column spp of d1 has an NA value in column state. However, in d2 the observation C in column spp has the value Z in column state. How can I update the state column of d1, adding the state observations from d2 when there is a spp observation that is common to both d1 and d2?

colin
  • 2,606
  • 4
  • 27
  • 57

1 Answers1

0

We can do a join on the 'spp' and assign the 'state' with the second dataset 'state' column i.e. i.state

d1[d2, state := i.state, on = .(spp)]
akrun
  • 874,273
  • 37
  • 540
  • 662