cpp11 get all row values for a single column

Hi everyone!

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)

Thanks in advance!

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

Created on 2021-10-21 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.