FAQ Database Discussion Community


Rcpp scoping of free variables

r,rcpp,scoping
Say that I have a C++ function dosomething(z) that has a single input variable z, but also a "free" variable located within it (say y). I want to be able to design the scoping so that when I run the Rcpp function, it finds the free variable within the R...

Creating objects of R S4 classes in Rcpp?

r,rcpp
There is an S4 R class whose object I need to create in Rcpp. Is it possible to do this, and if yes, how?

RcppEigen: Fastest way to square a positive definite matrix?

r,matrix,rcpp
Suppose I have a positive definite matrix S. I would like to compute S %*% S using RcppEigen. I could do: using Eigen::Map; using Eigen::MatrixXd; const Map<MatrixXd> S(as<Map<MatrixXd> >(AA)); const MatrixXd SS(S * S); return wrap(SS); But this seems wasteful, given that S is positive definite (though it does improve...

how to match versions of Rcpp and RcppArmadillo for older R on windows?

r,rcpp
I created RcppArmadillo package on windows (Win 7, 64 bit) using R 3.1.2 and the latest versions of Rcpp 0.11.3 and RcppArmadillo 0.4.600.0. Package compiles, installs, and runs fine. Afterwards i wrote some code to use BigMatrix from bigmemory package with my RcppArmadillo package. As it turns out bigmemory is...

What's causing this strange random number generator behaviour?

r,plyr,rcpp
I'm trying to make some reproducible examples for some simulation studies, so I'm using set.seed to get consistent results from the "random" part. However, I noticed I was sometimes getting different results. I've tried to narrow this down to a minimal reproducible example, but it seems to take multiple elements...

How to speed up or vectorize a for loop?

r,performance,for-loop,vectorization,rcpp
I would like to increase the speed of my for loop via vectorization or using Data.table or something else. I have to run the code on 1,000,000 rows and my code is really slow. The code is fairly self-explanatory. I have included an explanation below just in case. I have...

How do I tell the C++ compiler on a supercomputer that my R package requires C++0x?

c++,r,c++11,rcpp
I have written and built an R package that depends on Rcpp and requires the C++0x standard (for using the tgamma function in C++). I have tested the package on various desktop computers and operating systems, and it always seems to install and work fine. However, I would also like...

vectorized exponent for pow in Rcpp

r,rcpp
Rcpp allows to vectorize some operations, which is great. But for pow only the base number can be a vector, not the exponent. Typically, on compilation: #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector puissancedCpp(NumericVector base, double exp){ return pow(base,exp); } works but not: #include <Rcpp.h> using namespace Rcpp; //...

Error installing and running rcpp

r,rcpp
I'm pretty new to R so apologies for a stupid question. I'm trying to get rcpp running but I'm stuck in an endless loop of R asking me to re-install RTools. I broadly followed the code in this blog post, although first time off I installed everything by hand &...

return NA value in NumericVector Rcpp unexpected behavior

r,rcpp,na
I am writing a cpp function to replace any NA values with the next non-na value. Code works properly regarding the replacement, however I want to return back the NA values for those that don't have a later non-NA value. Eg: fill_backward(c(1, NA, 2)) --> 1, 2, 2 fill_backward(c(1, NA,...

How do I get an Armadillo function to NOT print an error when inverting a singular matrix?

c++,r,rcpp,armadillo
A buddy and I are working on an R package and using the RcppArmadillo package for some of the heavier matrix algebra. It's going pretty sweet so far but we're having a little issue concerning matrix inversion. Long story short, a program is searching for a particular type of matrix...

How to effectively combine a list of NumericVectors into one large NumericVector?

c++,r,rcpp
I wrote the following Rcpp code which compiles, but the speed is not fast as expected. // [[Rcpp::export]] NumericVector combine_list_to_vec (const Rcpp::List& list) { int list_size = list.size(); int large_vec_size = 0; IntegerVector start_index(list_size); IntegerVector end_index(list_size); for (int ii = 0; ii < list_size; ii++) { NumericVector vec = list[ii];...

Named indexing for a matrix

r,rcpp
I am trying to index a matrix with names. The usual method gives errors: NumericMatrix mytest(NumericVector v) { NumericMatrix ans(v.length(), v.length()); rownames(ans) = v; float y = ans("1",0); NumericVector x = ans.row("1"); return (ans); } I looked over in Matrix.h and the matrix unit tests in rcpp and couldn't find...

Paste the elements of two columns [duplicate]

r,performance,data.frame,paste,rcpp
This question already has an answer here: Speedy/elegant way to unite many pairs of columns 3 answers I have a data.frame of the following kind set.seed(12) d = data.frame(a=sample(5,x=1:9), b=sample(5,x=1:9), c=sample(5,x=1:9), d=sample(5,x=1:9), e=sample(5,x=1:9), f=sample(5,x=1:9)) d # a b c d e f # 1 1 1 4 4 2...

using Rcpp with boost/regex ,Error in eval(expr, envir, enclos) : object 'libboost_regex' not found

c++,r,boost,rcpp
when using Rcpp with boost/regex, Build&reload show Error in eval(expr, envir, enclos) : object 'libboost_regex' not found Error : unable to load R code in package ‘genia’ ERROR: lazy loading failed for package ‘genia’ I have set Sys.setenv(PKG_LIBS="-L/Users/name/software/cpp_boost/lib -lboost_regex") Sys.setenv(PKG_CPPFLAGS="-I/Users/name/software/cpp_boost/include -I../inst/include") but, using sourceCpp(), It's ok. I want to know...

Rcpp NumericalMatrix data type, global declaration

c++,r,boost,rcpp,odeint
I'm fairly new with C++ and I'm trying to use it via Rcpp to speed up my R code. The below code integrates from from t0 to t1- this is done in the "lorenz" function. Test4 integrates using "lorenz" "counts" number of times. However at time "t1" the state of...

How to initialize NumericVector to a specific size after it has been declared?

c++,r,rcpp
I wrote the following Rcpp code which compiles but does not give the expected result. // [[Rcpp::export]] RObject test_1 (Rcpp::NumericVector& x) { NumericVector x1; if (x.size() < 5) { NumericVector x1(x.size()*3); for (int ii = 0; ii < x.size(); ii++) { x1[ii] = sqrt(x[ii]); } } else { NumericVector x1(x.size()*2);...

.Rd file generation in a package using Rcpp

r,rstudio,rcpp
I created a test package containing Rcpp code using Rcpp.package.skeleton() command. All the required files as per vignette were generated and I was able to compile the package. I tried to add roxygen2 style comments to the example code #include <Rcpp.h> using namespace Rcpp; //' @param none required //' @return...

Performance of runif

c++,r,memory,rcpp
I am working on a custom bootstrap algorithm for a specific problem, and as I want a large number of replicates I do care about performance. In this regard, I have some questions on how to use runif properly. I'm aware that I could run benchmarks myself, but C++ optimization...

Using colon (':') to access elements in an array in C++ (in Rcpp)

c++,r,rcpp
I am trying to run the following code. Frankly I know C++ only little but I want to get the following function run. Can you help me run this silly example? cppFunction( 'NumericVector abc(int x, int x_end, NumericVector y) { NumericVector z; int x1 = x + x_end; z =...

Make cumulative sum faster

r,rcpp
I'm trying to take cumulative sums for each column of a matrix. Here's my code in R: testMatrix = matrix(1:65536, ncol=256); microbenchmark(apply(testMatrix, 2, cumsum), times=100L); Unit: milliseconds expr min lq mean median uq max neval apply(testMatrix, 2, cumsum) 1.599051 1.766112 2.329932 2.15326 2.221538 93.84911 10000 I used Rcpp for comparison:...

Error when calling Rcpp function from Tableau. How to interpret and debug Rserve logs?

c++,r,rcpp,tableau,rserve
I'm having a lot of trouble connecting an R function I wrote to Tableau. The function relies on Rcpp. In R, if I call prob_1_beats_2(1, 2, 3, 4) it works just fine. However, when I try to connect to Tableau using Rserve, I get this error: Error in eval(expr, envir,...

Eigen 3 - Slicing a MatrixXd to reverse the columns order

c++,r,rcpp,eigen3
I need to reverse the order of the columns of a MatrixXd using RcppEigen. In R I would simply do > M = matrix(1:9, ncol = 3) > M [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > M = M[, 3:1] >...

how to get the determinant of a matrix using RcppEigen

c++,r,matrix,rcpp
I am brand new to Rcpp. I am trying to using the R package RcppEigen to get the determinant of a matrix. The following code is saved in a file and I use sourceCpp to use it. There is no compilation error when I use sourceCpp. When using getDeterminant(A) in...

Rcpp code error?

c,r,compiler-errors,rcpp
This code works well on R with Rcpp cppFunction(' double getMean (NumericVector x) { int n = x.length() ; double mn = 0.0 ; for (int it = 0 ; it < n ; it++) { mn += x(it) / n ; } return(mn) ; } ') but adding just...

Use .Call() to send an s4 object to a C struct

c,r,rcpp,s4
I would like to pass a simple s4 object into C and turn it into an simple struct. I'm picturing R code like setClass("MyClass", slots = list(x = "numeric", y = "integer")) r_instance = new("MyClass", x = rnorm(5), y = as.integer(1:10)) dyn.load("parse.so") .Call("parse", r_instance) with parse.c #include <R.h> #include <Rinternals.h>...

Fastest way to filter a data.frame list column contents in R / Rcpp

r,performance,data.table,dplyr,rcpp
I have a data.frame: df <- structure(list(id = 1:3, vars = list("a", c("a", "b", "c"), c("b", "c"))), .Names = c("id", "vars"), row.names = c(NA, -3L), class = "data.frame") with a list column (each with a character vector): > str(df) 'data.frame': 3 obs. of 2 variables: $ id : int 1...

Reproducing R rep with the times argument in C++ and Rcpp

r,rcpp
I'm learning to use Rcpp. I'd like to use C++ to replicate the rep function in R. Rcpp includes several sugar functions that correspond to rep in R. (see bottom of page 3 at: http://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-quickref.pdf. As I understand the documentation, the sugar functions rep, rep_each, and rep_len take two arguments...

fastLm() is much slower than lm()

r,rcpp
fastLm() is much slower than lm(). Basically, I just call lm() and fastLm() with the same formula and data, but fastLm() seems to be much slower than lm(). Is this possible? I just don't know how could this happen? dim(dat) #[1] 87462 90 ## library(Rcpp) library(RcppEigen) library(rbenchmark) benchmark(fastLm(formula(mez),data=dat),lm(formula(mez),data=dat)) test replications...

Rcpp swap function with NumericVector

r,swap,rcpp
As I was exploring Rcpp I came to realization that the following swap function // swap.cpp #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] void swap(NumericVector x) { double tmp = x[0]; x[0] = x[1]; x[1] = tmp; } does not perform the swap when passed an integer vector. For example,...

rcpp codes fails to load with boost library (as implemented in BH) when using boost::iostreams::gzip_decompress

r,boost,rcpp
I wish to read data from a .bz file. I am trying to do it using rcpp plus boost using the BH library. I am running R 3.2.0 on MacOSX 10.10.3, Rcpp version 0.11.6, and BH 1.58.0-1. Here is my code thus far: // [[Rcpp::depends(BH)]] #include <Rcpp.h> #include <iostream> #include...

Can Rcpp expose a C++ class method taking a reference to the same class?

c++,r,rcpp
Is it possible to use Rcpp to expose a C++ class to R when the class has a member taking an instance of that class? Example: #include <Rcpp.h> class Test { public: Test(int x): x_(x) {} int getValue() { return x_; } void addValue(int y) { x_ += y; }...

When does using RNGScope make a difference?

rcpp
In Rcpp documentation, I often find the recommendation to place Rcpp::RNGScope scope; before using random draws within Rcpp. I wondered what exactly this does, because I've only ever seen it described as "ensures RNG state gets set/reset". Then, I tested a bit, but I can't seem to come up with...

installing Rcpp on R compiled with intel composer on OSX Yosemite

r,clang,openmp,rcpp,intel-composer
Inspite of succeeding with the compilation of R-3.1.2 using the intel suite of compilers ver.2015.0.077 including MKL on my late 2014 MacBook Pro running Yosemite (outlined here), I am unable to install the excellent Rcpp package that I have been thoroughly enjoying thus far via the prepackaged binary R for...

Rcpp Power Set implementation : attempt to set index 8/8 in SET_VECTOR_ELT

r,rcpp
Consider the function which takes a set of elements as an input vector and returns the power set in a list: > pwr_set(letters[1:3]) [[1]] character(0) [[2]] [1] "a" [[3]] [1] "b" [[4]] [1] "a" "b" [[5]] [1] "c" [[6]] [1] "a" "c" [[7]] [1] "b" "c" [[8]] [1] "a" "b"...

Rcpp How to convert IntegerVector to NumericVector

r,rcpp
I was wondering how to convert Rcpp IntegerVector to NumericVetortor to sample three times without replacement of the numbers 1 to 5. seq_len outputs an IntegerVector and sample sample only takes an NumericVector // [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadilloExtensions/sample.h> #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector follow_path(NumericMatrix X, NumericVector y) {...

Customize where R looks for shared objects?

r,g++,rcpp,centos5,g++4.8
This question is similar to this previous question with respect to RcppArmadillo. Some quick context: I currently must work on a CentOS 5 system. Naturally, the compiler that comes with CentOS 5 was too old so we installed gcc-4.8.3. Now, others were concerned about back compatibility with the old compiler...

Rccp warning: “directory not found for option '-L/usr/local/Cellar/gfortran/4.8.2/gfortran'”

r,rcpp
This question relates to some others out there, like RccpArmadillo or element-wise-multiplication. However, my settings are such that I do not know what I have to edit/simlink to make Rccp run without giving me warnings. I am on an Mac 10.9 (mavericks) using the latest R version. At the very...

Matrix Multiplication Using NumericMatrix and NumericVector in Rcpp

matrix-multiplication,rcpp
I am wondering is there a way of calculating matrix multiplication using NumericMatrix and NumericVector class. I am wondering if there is any simple way to help me avoid the following loop to conduct this calculation. I just want to calculate X%*%beta. // assume X and beta are initialized and...

lineprof equivalent for Rcpp

r,performance,profiling,rcpp
The lineprof package in R is very useful for profiling which parts of function take up time and allocate/free memory. Is there a lineprof() equivalent for Rcpp ? I currently use std::chrono::steady_clock and such to get chunk timings out of an Rcpp function. Alternatives? Does Rstudio IDE provide some help...

Questions about Rcpp

r,rcpp
I wrote the following calculation in R. However, this is slow used in a number of "for loops" . I tried to write similar calculations by using Rcpp . But it was an error. Please be correct my code. # R data <- matrix(1: 100, ncol = 5, nrow =...

Building a tiny R package with CUDA and Rcpp

r,cuda,rcpp
I'm working on a tiny R package that uses CUDA and Rcpp, adapted from the output of Rcpp.package.skeleton(). I will first describe what happens on the master branch for the commit entitled "fixed namespace". The package installs successfully if I forget CUDA (i.e., if I remove the src/Makefile, change src/rcppcuda.cu...

Rcpp: Include header from package into cppFunction

r,rcpp
I have a package that uses Rcpp. It has different C++ function defined int src/testr.h. Now at some point I need to generate Rcpp functions (using cppFunction or cxxfunction) that use things defined in src/testr.h. How can I do that? I tried, > cxxfunction(signature(x="list") includes = c('#include "testr.h"'), body=sprintf(template, name,...

Speeding up a strangely slow Rcpp function

r,rcpp
I want to rewrite an expensive R function using Rcpp. As I am new to this topic I experimented with some very simple stuff. I wrote the following function: Rcpp::cppFunction(' std::vector<int> test_C(double a) { std::vector<int> indices; indices.reserve(2); indices.push_back(a); indices.push_back(a); return (indices); } ') Now that works all well regarding the...

C++ compiling error while compiling R package on Winbuild

c++,r,rcpp,cran
My package (slfm) uses Rcpp to connect C++ code to R. Its check runs OK on linux, but I get this error when trying to compile it using WinBuild: * installing *source* package 'slfm' ... ** libs *** arch - i386 g++ -I"D:/RCompile/recent/R-3.1.2/include" -I"d:/RCompile/CRANpkg/lib/3.1/Rcpp/include" -I"d:/RCompile/CRANpkg/lib/3.1/RcppArmadillo/include" -I"d:/Rcompile/CRANpkg/extralibs215/local215/include" -O3 -Wall -mtune=core2 -c...

Print integer vector from Rcpp function

r,rcpp
How do I print integer vector from Rcpp function? In my function, I would like to print IntegerVector a. In R I am calling this function using for example compnz_next(5,3,c(1,2,2)) #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] IntegerVector compnz_next(int n, int k, IntegerVector a) { bool more = true; int...

Equivalent of Is.factor and is.numeric in RCPP

r,rcpp
I am trying to port some R code for a distance function to RCPP: distanceFunction <- function(row1, row2){ distance = 0 for(f in names(row2)) if (is.factor(row2[[f]])){ if (!(row2[[f]] == row1[[f]])) distance = distance + 1 } else if(is.numeric(row2[[f]])) { distance = distance + abs(row2[[f]] - row1[[f]]) } distance } Unfortunately...

Rcpp: Apply lfactorial to NumericVector

r,rcpp
What is the nicest/easiest way to apply the lfactorial function to a NumericVector in Rcpp. In R I would have something like this: > vec <- c(1,2,3,4) > lfactorial(vec) [1] 0.0000000 0.6931472 1.7917595 3.1780538 In Rcpp, suppose I have: NumericVector vec = NumericVector::create(1,2,3,4); What is the nicest way to apply...

How to call an R function in a particular R package from Rcpp

r,rcpp
I am wondering if there is a way to call an R function in a particular package from Rcpp. For example, I would like to call "dtrunc" function in "truncdist" package in my Rcpp file. Is it possible to do that?

Fastest way to transpose a list in R / Rcpp

r,performance,rcpp
I have a list: ls <- list(c("a", "b", "c"), c("1", "2", "3"), c("foo", "bar", "baz")) ls #> [[1]] #> [1] "a" "b" "c" #> [[2]] #> [1] "1" "2" "3" #> [[3]] #> [1] "foo" "bar" "baz" which I wish to "transpose" to give: resulting_ls #> [[1]] #> [1] "a"...

Error with compiling RInside examples under Windows

c++,r,rcpp,rinside
I am currently trying to use RInside to do some plots in backtesting, inspired by Saving Lattice Plots with RInside and Rcpp. I came with problem by compiling RInside . And before digging into my question, I've already looked up the three previous questions: Problem with compiling RInside examples under...

rcpp updating data in base environment

r,rcpp
I am working on a simple matching algorithm in Rcpp which is taking a number of individuals (I), a number of schools (J), a number of submitted choices (nc), a priority ranking of individuals (pos), the number of vacancy (emp), and the true choices.. #include <Rcpp.h> using namespace Rcpp; //[[Rcpp::export]]...

R parallel write SEXP structure

c++,r,multithreading,rcpp
I am working on a data processing module in R using C/C++ code, mainly for speed reasons. Here is a list of facts of my problem. The final outcome data is a list of string vectors and takes between 20MB to 200MB of memory. The data processing can be fit...

shared library apparently not containing any routines

r,shared-libraries,rcpp
I'm trying to make an R interface to the C++ library Faddeeva (various types of complex error functions); unfortunately I have very little experience in calling external code in R and it's proving quite a challenge. My naive attempt, R CMD SHLIB Faddeeva.cc produced a shared library Faddeeva.so, which I...

Setting *only* column names in Rcpp

r,rcpp
I want to set a matrix's column names only using Rcpp, but leave the row names unchanged. So far as I can tell, the dimnames attribute only sets both. For example: R extension in C, setting matrix row/column names http://dirk.eddelbuettel.com/code/rcpp/Rcpp-FAQ.pdf (p.13) Here's a minimal example of what I want to...

__result not declared in this scope

rcpp
Hi I am getting an error "__result was not declared in this scope". There is no variable "result" any more. "outResult" was named "result" before. But renamed. I did cut down the code. It makes no sense but is simple now and I get the error. Are there any temporary...