0

I am trying to comine two data frames such that I match the values in the vector called vec by their index number.

vec=c(-2,-5)

y=as.data.frame(cbind(0:(length(c(vec))-1)*2+1,c(vec)))

  V1 V2
1  1 -2
2  3 -5

x=as.data.frame(1:4,names="V1"); names(x)="V1"

  V1
1  1
2  2
3  3
4  4

What I want is a dataframe to look like this

  V1  V2
1  1  -2
2  2  NA
3  3  -5
4  4  NA

I have trying to get this command to work but as of no luck

merge(x,y,by.x="V1")
jessica
  • 1,325
  • 2
  • 21
  • 35
  • 1
    You just want a left join: `merge(x, y, all.x=TRUE)` – MrFlick Mar 29 '20 at 22:49
  • Thanks Mr.Flick though I wish you had kept my example up. The answer you suggested in another post was alot more complicated. This was just a much simpler answer with your beauitful simple answer. – jessica Mar 29 '20 at 23:48
  • I just think It's a simple question with a simple answer and I know many R users are looking for this quick answer rather than along one. My question was similar to how someone who is used to Vlookup in excel is thinking. – jessica Mar 29 '20 at 23:51

1 Answers1

1

Try a left_join()

z <- left_join(x, y, by="V1")
print(z)

Output:

  V1 V2
1  1 -2
2  2 NA
3  3 -5
4  4 NA
Reeza
  • 20,510
  • 4
  • 21
  • 38
  • Thanks Reeza. I would appreciate if you could vote to reopen. I think this is a simple question with a simple example and answer that many R users want. – jessica Mar 29 '20 at 23:54