0

My english doesn't permit me to ask this question exactly how it should be asked so I'll give examples. I have one dataframe like this:

A  0   20
A  20  30
A  30  50
A  50  100
...
B  0  30
B  30 150
...

And the other like:

A  20  30   1.0
A  50  100  2.5
B  30  150  -1.02

And basically I want to modify the first dataset so it would have the values from the fourth column of the second dataframe if values in first three columns are equal in both dataset and zeroes (or NAs) in other case:

A  0   20  0
A  20  30  1.0
A  30  50  0
A  50  100 2.5
...
B  0   30  0
B  30  150 -1.02 

Of course I can do that with ugly for loops but my intuition tells me that there are more elegant ways of solving this problem, maybe with some advanced packages.

Poiu Rewq
  • 182
  • 13

1 Answers1

0

like the comments suggested, merge() implements a left join:

a <- data.frame(  "a" = c("A","A","A","A","B","B"), "b" = c(0,20,30,50,0,30), "c" = c(20,30,50,100,30,150) )
b <- data.frame( "a" = c("A","A","B"), "b"= c(20,50,30), "c" = c(30,100,150) , "d" = c(1,2.5,-1.02) )

merge(x = a, y = b , by = c("a","b","c") , all.x = TRUE )

all.x tells merge to keep the examples in a that did not match

David Heckmann
  • 2,899
  • 2
  • 20
  • 29