I am writing a function with cpp11 that, ideally, uses a user provided R function to act on each column of a user provided matrix through a for loop. However, I was not able to extract the values of an entire column to use it in the user provided function. I also couldn't find how to do this after looking cpp11 documentation up.
Reproducible example:
require(cpp11)
cpp11::cpp_source(code='
#include <cpp11.hpp>
using namespace cpp11;
namespace writable = cpp11::writable;
[[cpp11::register]]
sexp test_f(cpp11::doubles_matrix<> x, cpp11::function f) {
int n = x.ncol();
writable::doubles out(n);
cpp11::unwind_protect([&] {
for (int i = 0; i < n; ++i) {
out[i] = f(x[???][i]); // what should I use instead of ???
}
});
return out;
}')
f <- function(x) sum(x) # toy example
test_f(matrix(1.2:9.2, 3, 3), f)
First you should ensure you are iterating by column rather than by row, and then you will need to collect the values of each column into a doubles object before passing it to the function.
Something like this
cpp11::cpp_source(code='
#include <cpp11.hpp>
using namespace cpp11;
namespace writable = cpp11::writable;
[[cpp11::register]]
cpp11::doubles test_f(cpp11::doubles_matrix<cpp11::by_column> x, cpp11::function f) {
writable::doubles out;
cpp11::unwind_protect([&] {
for (auto col : x) {
cpp11::writable::doubles dbl_col;
for (auto val : col) {
dbl_col.push_back(val);
}
out.push_back(f(dbl_col));
}
});
return out;
}')
x <- matrix(1.2:9.2, 3, 3)
colSums(x)
#> [1] 6.6 15.6 24.6
f <- function(x) sum(x) # toy example
test_f(x, f)
#> [1] 6.6 15.6 24.6