celestialgod

move to left Rcpp version

Sep 12th, 2015
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.81 KB | None | 0 0
  1. library(data.table)
  2. library(plyr)
  3. library(dplyr)
  4. library(magrittr)
  5. library(Rcpp)
  6.  
  7. mat = fread('No, A, B, C, D, E, F, G
  8. 1, 1, 3, 0, 0, 4, 2, 1
  9. 2, 1, 0, 0, 0, 2, 0, 3
  10. 3, 0, 1, 0, 3, 0, 0, 0
  11. 4, 1, 3, 2, 1, 0, 0, 0
  12. 5, 0, 6, 0, 0, 0, 0, 0
  13. 6, 0, 0, 0, 0, 2, 2, 1
  14. ') %>% as.matrix
  15.  
  16. sourceCpp(code = '
  17. #include <Rcpp.h>
  18. using namespace Rcpp;
  19.  
  20. // [[Rcpp::export]]
  21. NumericMatrix move_left_f(NumericMatrix mat, double replacedValue = 0.0, bool drop = false) {
  22.  int nc = mat.ncol(), nr = mat.nrow();
  23.  std::vector< std::vector<double> > out(nr);
  24.  for (int j =0; j < nc; j++)
  25.  {
  26.    for (int i = 0; i < nr; i++)
  27.    {
  28.      if (mat(i,j)!=replacedValue)
  29.        out[i].push_back(mat(i,j));
  30.    }
  31.  }
  32.  std::size_t outNumCol = 0;
  33.  if (drop)
  34.  {
  35.    for (int i = 0; i < nr; i++)
  36.      outNumCol = (outNumCol > out[i].size()) ? outNumCol : out[i].size();
  37.  }
  38.  else
  39.    outNumCol = nc;
  40.  NumericMatrix outMat(nr, outNumCol);
  41.  for (int j = 0; j < (int) outNumCol; j++)
  42.  {
  43.    for (int i = 0; i < nr; i++)
  44.    {
  45.      if (j < (int) out[i].size())
  46.        outMat(i, j) = out[i][j];
  47.      else
  48.        outMat(i, j) = 0.0;
  49.    }
  50.  }
  51.  return outMat;
  52. }')
  53. move_left_f(mat, 0.0, FALSE)
  54. #      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
  55. # [1,]    1    1    3    4    2    1    0    0
  56. # [2,]    2    1    2    3    0    0    0    0
  57. # [3,]    3    1    3    0    0    0    0    0
  58. # [4,]    4    1    3    2    1    0    0    0
  59. # [5,]    5    6    0    0    0    0    0    0
  60. # [6,]    6    2    2    1    0    0    0    0
  61. move_left_f(mat, 0.0, TRUE)
  62. #      [,1] [,2] [,3] [,4] [,5] [,6]
  63. # [1,]    1    1    3    4    2    1
  64. # [2,]    2    1    2    3    0    0
  65. # [3,]    3    1    3    0    0    0
  66. # [4,]    4    1    3    2    1    0
  67. # [5,]    5    6    0    0    0    0
  68. # [6,]    6    2    2    1    0    0
Advertisement
Add Comment
Please, Sign In to add comment