Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Created January 16, 2025 08:14
Show Gist options
  • Save abikoushi/c5ed8c4fa3d8b5b0467b2faea9dab627 to your computer and use it in GitHub Desktop.
Save abikoushi/c5ed8c4fa3d8b5b0467b2faea9dab627 to your computer and use it in GitHub Desktop.
filtering rows in mtx file using Rcpp
#include "RcppArmadillo.h"
// [[Rcpp::depends(RcppArmadillo)]]
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace Rcpp;
// [[Rcpp::export]]
void rowfilter_mtx(const std::string & readtxt,
const std::string & writetxt,
const arma::vec & rowind){
int x;
//int y;
//double v;
std::ifstream file(readtxt);
std::string str;
int index = 0;
//int n = 0;
std::ofstream myfile;
myfile.open(writetxt);
while (std::getline(file, str)){
if(index <= 2){
myfile << str + "\n";
}else{
std::stringstream ss(str);
std::vector<std::string> svec;
while( ss.good() ){
std::string substr;
getline(ss, substr, ' ');
svec.push_back(substr);
}
x = stoi(svec[0]);
//y = stoi(svec[1]);
//v = stod(svec[2]);
if(arma::any(rowind==x)){
myfile << svec[0] + " " + svec[1] + " " + svec[2] + "\n";
}
}
index++;
}
myfile.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment