Created
January 16, 2025 06:06
-
-
Save abikoushi/9fa1d5e52ba9b11ff216ecfe5cf2eb13 to your computer and use it in GitHub Desktop.
rowwise mean and variance from mtx file using Rcpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "RcppArmadillo.h" | |
// [[Rcpp::depends(RcppArmadillo)]] | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
using namespace Rcpp; | |
// [[Rcpp::export]] | |
List rowmeanvar_mtx(const int & n_row, const int & n_col, | |
const std::string & readtxt) { | |
int x; | |
int y; | |
double v; | |
std::ifstream file(readtxt); | |
std::string str; | |
int index = 0; | |
int n = 0; | |
arma::vec vout = arma::zeros<arma::vec>(n_row); | |
arma::vec v2out = arma::zeros<arma::vec>(n_row); | |
while (std::getline(file, str)){ | |
if(index > 2){ | |
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]); | |
vout(x-1) += v; | |
v2out(x-1) += pow(v,2); | |
} | |
index++; | |
} | |
vout /= n_col; | |
v2out /= n_col-1; | |
v2out -= pow(vout,2); | |
return List::create(Named("mean")=vout, Named("var")=v2out); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment