I have a dataframe like:
> df <- data.frame(id=c(015,335,625,789), B=c(8,19,8,6), C=c(4,1,4,6), Source=c("Gk", "Ap", "Ap", "Kh"))
> df
id B C Source
1 015 8 4 Gk
2 335 19 1 Ap
3 625 8 4 Ap
4 789 6 6 Kh
And another dataframe:
p <- data.frame(id=c(335,625, 789), B2 = c(5,3,4))
p
id B2
1 335 5
2 625 3
3 789 4
I want replace those values in column B of df by the values in B2 of p, but only for those with same id in both dataframes and df$Source == "Ap".
The final dataframe should be:
id B C Source
1 015 8 4 Gk
2 335 5 1 Ap
3 625 3 4 Ap
4 789 6 6 Kh
I know how to replace the whole column by zeros or NAs, etc, but I just want to replace those that follow the mentioned condition (and without for loops...). How can I achieve this?
dfyour id is not the same asidas in the definition ofdf. Please edit this.