How can I implement a simple merge function to merge two matrices each having two columns with a common column x
using Rarmadillo? In other words, I want a function my_merge_cpp(mat1, mat2)
which will give the same result using the following R code:
mat1 = as.matrix(data.frame(x=1:5, y1=2:6)) ## an example
mat2 = as.matrix(data.frame(x=3:7, y2=3:7)) ## an example
as.matrix(merge(mat1, mat2, all=FALSE))
I would use data.table
. Try it with larger data, I would be rather surprised to see you beat it with a home-grown Rcpp or RcppArmadillo solution.
library(data.table)
mat1 <- data.table(x=1:5, y1=2:6) ## an example
mat2 <- data.table(x=3:7, y2=3:7) ## an example
mat1[mat2, on="x", nomatch=NULL]
Demo
R> library(data.table)
R> mat1 <- data.table(x=1:5, y1=2:6) ## an example
R> mat2 <- data.table(x=3:7, y2=3:7) ## an example
R> mat1[mat2, on="x", nomatch=NULL]
x y1 y2
1: 3 4 3
2: 4 5 4
3: 5 6 5
R>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With