STL Transform

[This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The STL transform function can be used to pass a single function over a vector. Here we use a simple function square().

#include <Rcpp.h>

using namespace Rcpp;

inline double square(double x) { return x*x ; }

// [[Rcpp::export]]
std::vector<double> transformEx(const std::vector<double>& x) {
    std::vector<double> y(x.size());
    std::transform(x.begin(), x.end(), y.begin(), square);
    return y;
}

  x <- c(1,2,3,4)
  transformEx(x)


[1]  1  4  9 16

A second variant combines two input vectors.

inline double squaredNorm(double x, double y) { return sqrt(x*x + y*y); }

// [[Rcpp::export]]
NumericVector transformEx2(NumericVector x, NumericVector y) {
    NumericVector z(x.size());
    std::transform(x.begin(), x.end(), y.begin(), z.begin(), squaredNorm);
    return z;
}

  x <- c(1,2,3,4)
  y <- c(2,2,3,3)
  transformEx2(x,y)


[1] 2.236 2.828 4.243 5.000

To leave a comment for the author, please follow the link and comment on their blog: Rcpp Gallery.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)