I got tableA, which contains a numeric variable, CdTaller (e.g. 1948675).

I also got tableB, which contains two variables: Id (e.g. 2513978) and Name (e.g. "JOSE MANUEL PEREZ")

I want to add a new column to tableA, Name_Taller, which contains a name for those CdTaller which correspond to the Id variable of tableB, so I do the following:

tableA[, Name_Taller := tableB[Id==tableA\$CdTaller]$Name]

However, for those CdTaller of tableA that are not in tableB, R recycles the new variable Name_Taller:

Warning message:
In \`[.data.table\`(tableA, , \`:=\`(Name, tableB[Id ==  :
  Supplied 867324 items to be assigned to 947871 items of column 'Name'
  (recycled leaving remainder of 80547 items).

So for the tableA$CdTaller == '1320402', which can't be found in tableB, R still adds a Name_Taller which actually corresponds to CdTaller == '4430219', because of this recycling.

The question is: how can I avoid this recycling, so that R only adds a NA or empty string to those rows containing a CdTaller not found in tableB? Is there any parameter in data table I can use for this purpose?


1 Answer 1


What you want to do is join-like behaviour that is among others documented here: joins and others

To make things readable here a version with dplyr

ex1 <- data.frame(id = 1:10, name = replicate(10, paste(sample(letters[1:5], size = 2), collapse = "")))

ex2 <- data.frame(otherinfo = (1:5)+50, othername = replicate(5, paste(sample(letters[1:5], size = 2), collapse = "")))

dplyr::left_join(ex1, ex2, by = c(name = "othername"))

   id name otherinfo
1   1   ac        NA
2   2   ac        NA
3   3   ab        NA
4   4   da        53
5   5   ab        NA
6   6   cb        NA
7   7   eb        NA
8   8   de        NA
9   9   ad        NA
10 10   ec        52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.