Rcpp exercises given by Hadley Wickem

For the exercises given in the middle here . I would like to know the answers ... to test my understanding.

I'm not sure what the R functions are baseall about, but here are my guesses:

f1is a function that calculates the sum x_i / i from i = 1 to n, where xi is the vector input in f1and n is the length x

f2matches function cumsum()inbase

f3is a function any()inbase

f4 checks the first member of the list that your pred function input returns a TRUE statement

f5 gets the minimum value when comparing values ​​for vectors x and y (which can have different lengths)

And I think that the answers of the second half of the exercise are as follows (any improvements / suggestions for effectiveness are welcome):

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
bool allC(LogicalVector x) {
  int n = x.size();

  for(int i = 0; i < n; ++i) {
    if (!(x[i])) {
      return false;
    } else {}
  }
  return true;
}

// [[Rcpp::export]]
NumericVector cumprodC(NumericVector x){
  int n = x.size();
  NumericVector out(n);

  out[0] = x[0];

  for(int i=1; i<n; i++){
    out[i] = out[i-1] *  x[i];
  }
  return out;
}

// [[Rcpp::export]]
NumericVector cumminC(NumericVector x){
  int n = x.size();
  NumericVector out(n);

  out[0] = x[0];

  for(int i=1; i<n; i++){
    out[i] = std::min(out[i-1],x[i]);
  }
  return out;
}

// [[Rcpp::export]]
NumericVector cummaxC(NumericVector x){
  int n = x.size();
  NumericVector out(n);

  out[0] = x[0];

  for(int i=1; i<n; i++){
    out[i] = std::max(out[i-1],x[i]);
  }
  return out;
}

// [[Rcpp::export]]
NumericVector diffC(NumericVector x){
  int n = x.size();
  NumericVector out(n-1);

  for(int i=0; i<(n-1); i++){
    out[i] = x[i+1]-x[i];
  }
  return out;
}

// [[Rcpp::export]]
NumericVector rangeC(NumericVector x){
  int n = x.size();
  NumericVector out(2);

  out[0] = x[0];
  out[1] = x[0];

  for(int i=0; i<n; i++){
    out[0] = std::min(out[0],x[i]);
    out[1] = std::max(out[1],x[i]);
  }
  return out;
}

// [[Rcpp::export]]
double varC(NumericVector x){
  int n = x.size();
  double sum_of_x;
  double sum_of_sqr;

  sum_of_x = 0.0;
  sum_of_sqr = 0.0;

  for(int i=0; i<n; i++){
    sum_of_x += x[i];
    sum_of_sqr += x[i]*x[i];
  }

  return (sum_of_sqr - (sum_of_x*sum_of_x)/n)/(n - 1);
}
+4

Source: https://habr.com/ru/post/1525414/


All Articles