Reputation: 1355
I am trying to comine two data frames such that I match the values in the vectors called vec
by their index number. I am looking for an intuitive vlookup function.
vec=c(-2,-5)
vec2=c(11,17)
y1=as.data.frame(cbind(0:(length(c(vec))-1)*2+1,c(vec)))
V1 V2
1 1 -2
2 3 -5
y2=as.data.frame(cbind(0:(length(c(m$coefficients))-1)*2+2,c(vec2)))
V1 V2
1 2 11
2 4 15
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 11
3 3 -5
4 4 17
So far I was able to do the first merge
c1=merge(x, y1, all.x=TRUE)
V1 V2
1 1 -2
2 2 NA
3 3 -5
4 4 NA
But unable to do the second with
c2=merge(c1, y2, all.x=TRUE)
Upvotes: 0
Views: 137
Reputation: 886948
Another option is rbindlist
from data.table
library(data.table)
rbindlist(list(y1, y2)[x, on = .(V1)]
Upvotes: 0
Reputation: 388817
You can rbind
y1
and y2
and then merge
with x
.
merge(x, rbind(y1, y2), by = 'V1')
# V1 V2
#1 1 -2
#2 2 11
#3 3 -5
#4 4 15
Same logic using dplyr
:
library(dplyr)
bind_rows(y1, y2) %>% inner_join(x, by = 'V1')
Upvotes: 1