0

I need to update all the values of a column, using as reference another df.

The two dataframes have equal structures:

cod   name    dom_by
1       A        3
2       B        4
3       C        1
4       D        2

I tried to use the following line, but apparently it did not work:

df2$name[df2$dom_by==df1$cod] <- df1$name[df2$dom_by==df1$cod]

It keeps saying that replacement has 92 rows, data has 2.

(df1 has 92 rows and df2 has 2).

Although it seems like a simple problem, I still can not solve it, even after some searches.

  • 2
    It's not clear what you want to do. If you look at `df2$dom_by==df1$cod` you'll see that the df2's part is "recycled" 46 = 92/2 times. Maybe post a small self-contained example to illustrate. (I guess 92 rows are not required.) Some more guidance is here: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/28481250#28481250 – Frank Jul 12 '19 at 00:01
  • `match` is typically used for stuff like this. `==` is pairiwise, i.e., 1st element to 1st element, 2nd element to 2nd element, etc. You want 1st element to any element, 2nd element to any element.... `df2$name[df2$dom_by %in% df1$cod] = df1$name[match(df2$name[df2$dom_by %in% df1$cod], df1$cod)]`, I think. You can leave out the `[df2$dom_by %in% df1$cod]` parts if all `df2$dom_by` are in `df1$cod` - it's only needed if it is a partial update. – Gregor Thomas Jul 13 '19 at 12:10

0 Answers0