Reputation: 152
I want to merge two matrices (or update one matrix) which contains ID, coordinates (x,y) and year. Let's say that one matrix is from year 2011 and another from 2012.
Year 2011)
ID x y year
1 5000001 5000000 11
2 5000002 5000000 11
3 5000003 5000000 11
4 5000004 5000000 11
Year 2012)
ID x y year
3 5000003 5000001 12
4 5000004 5000001 12
5 5000005 5000000 12
6 5000006 5000000 12
7 5000007 5000000 12
Newer coordinates should always replace older ones. Therefore, in the example ID 3 aand 4's coordinates should be updated and ID 5-7 should be added / merged to matrix. What is the most efficient way to a) replace old coordinates and b) add new coordinates into matrix?
So far I've made vectors containing unique ID's (v1, v2) for each year and based on those I've got the ID's that are not in the most recent data (-> v3).
The real question is what is the proper loop or if-statement to search through the v3 ID-vector and add the coordinate values of those ID's into the recent data matrix (2012)? Forgive me, I'm not very good with these yet.
I hope this was clear enough.
Upvotes: 1
Views: 179
Reputation: 14366
If your matrices are called m2011 and m2012, it sounds like you just want to add to m2012 those rows of m2011 that have no IDs in m2012.. right?
So just
newmatrix <- rbind(m2012,
matrix(m2011[!(m2011[, "ID"] %in% m2012[, "ID"])], ncol = ncol(m2011)))
newmatrix[, "year"] <- 12
should work.
(If you then want to sort it by ID, then newmatrix <- newmatrix[order(newmatrix[, "ID"]), ]
)
Upvotes: 2