3

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?

1
  • in df your id is not the same as id as in the definition of df. Please edit this. Commented Jun 8, 2016 at 13:47

1 Answer 1

2

One way is ,

df[df$Source == "Ap", "B"] <- p[p$id %in% df[df$Source == "Ap", "id"] , "B2"]


#   id B C Source
#1  15 8 4     Gk
#2 335 5 1     Ap
#3 625 3 4     Ap
#4 789 6 6     Kh
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly what I was looking for. Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.