Complicated title but here is a simple example of what I am trying to achieve:
d <- data.frame(v1 = c(1,2,3,4,5,6,7,8),
v2 = c("A","E","C","B","B","C","A","E"))
m <- data.frame(v3 = c("D","E","A","C","D","B"),
v4 = c("d","e","a","c","d","b"))
Values in d$v2
should be replaced by values in m$v4
by matching the values from d$v2
in m$v3
The resulting data frame d
should look like:
v1 v4
1 a
2 e
3 c
4 b
5 b
6 c
7 a
8 e
I tried different stuff and the closest I came was: d$v2 <- m$v4[which(m$v3 %in% d$v2)]
I try to avoid any for-loops again! Must be possible :-) somehow... ;)
You could use a standard left join.
Loading the data:
Changing column name, such that I can join by column "v2"
Left joining and maintaining the order of data.frame d
Output:
You could try:
Edit
Here is another approach, to preserve the order: