Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge function in Rarmadillo

Tags:

r

rcpp

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))
like image 554
yliueagle Avatar asked Sep 21 '19 22:09

yliueagle


1 Answers

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.

Code
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> 
like image 195
Dirk Eddelbuettel Avatar answered Nov 15 '22 05:11

Dirk Eddelbuettel