Naveed Khan Wazir Naveed Khan Wazir - 1 month ago 10
R Question

Replace values from a column of one dataframe by values from another dataframe

I am trying to find the solution to this problem, I have two data frames, one is like

DF1

faID uID
1 20909
1 6661
1 1591
1 28065
1 42783
1 3113
1 21647
1 3825
2 134766
2 271168
2 16710
2 4071608
2 2046526
2 5081272


and another data frame look like this

DF2

uID user_cent_w
1591 15844
42783 466
21647 1514
29695 13958
94120 3615
83098 128
138776 709
90352 991
115384 8039
74483 128


I want to add a new column
user_cent
to
DF1
and the value of that column match the values of
uID
in
DF2
or replace the values of
uID
in
DF1
by the value of
user_cent_w
in
DF2
, i.e., if
uID
of
DF1
matches the value of
DF2
, i.e.,
user_cent_w
then replace
uID
by
user_cent_w
values.

I have tried the solution from

replace value in dataframe based on another data frame

but this replaces the values of
faID
as well in
DF1
.

My expected output will look like this:

faID user_cent_w
1 15844
1 466
1 1514
1 13958
1 3615
1 128
1 709
1 991
1 8039
1 128
1 6489
1 1781
2 5735
2 2072
2 128
2 128
2 2304
2 9301
2 1282

Answer Source

Try:

 library(dplyr)
 res <- left_join(df1,df2,by="uID")
 res$uID[!is.na(res$user_cent_w)] <- res$user_cent_w[!is.na(res$user_cent_w)]
 res[,1:2]
   res[,1:2]
  #  faID     uID
  #1     1   20909
  #2     1    6661
  #3     1   15844
  #4     1   28065
  #5     1     466
  #6     1    3113
  #7     1    1514
  #8     1    3825
  #9     2  134766
  #10    2  271168
  #11    2   16710
  #12    2 4071608
  #13    2 2046526
  #14    2 5081272

Or

  left_join(df1, df2, by="uID") %>% 
  mutate(uID=ifelse(is.na(user_cent_w), uID, user_cent_w)) %>%
  select(-user_cent_w)