ComenzarEmpieza gratis

Clonado de vectores

A diferencia de R, C++ usa un sistema de copia por referencia, lo que significa que si copias una variable y luego haces cambios en la copia, los cambios también se reflejarán en el original.

// [[Rcpp::export]]
NumericVector always_returns_two(NumericVector x) {
  // Make a copy
  NumericVector y = x;
  // Modify the copy
  y[0] = 2;
  // The changes also happen in the original
  return x[0];
}

Para evitar este comportamiento, tienes que usar la función clone() para copiar los datos subyacentes de la variable original a la nueva variable. La sintaxis es y = clone(x). En este ejercicio, hemos definido dos funciones para ti:

  • change_negatives_to_zero(): Toma un vector numérico, lo modifica reemplazando los números negativos por cero y devuelve tanto el vector original como la copia.
  • change_negatives_to_zero_with_cloning(): Hace lo mismo que la anterior, pero clona el vector original antes de modificarlo.

Este ejercicio forma parte del curso

Optimizar código de R con Rcpp

Ver curso

Instrucciones del ejercicio

  • Completa la definición de la función change_negatives_to_zero() estableciendo the_original como the_copy.
  • Completa la definición de la función change_negatives_to_zero_with_cloning() estableciendo the_copy como el clon de the_original.
  • Lee el contenido de la consola para comparar la salida de cada función.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

#include 
using namespace Rcpp;

// [[Rcpp::export]]
List change_negatives_to_zero(NumericVector the_original) {
  // Set the copy to the original
  NumericVector the_copy = ___;
  int n = the_original.size();
  for(int i = 0; i < n; i++) {
    if(the_copy[i] < 0) the_copy[i] = 0;
  }
  return List::create(_["the_original"] = the_original, _["the_copy"] = the_copy);
}

// [[Rcpp::export]]
List change_negatives_to_zero_with_cloning(NumericVector the_original) {
  // Clone the original to make the copy
  NumericVector the_copy = ___;
  int n = the_original.size();
  for(int i = 0; i < n; i++) {
    if(the_copy[i] < 0) the_copy[i] = 0;
  }
  return List::create(_["the_original"] = the_original, _["the_copy"] = the_copy);
}

/*** R
x <- c(0, -4, 1, -2, 2, 4, -3, -1, 3)
change_negatives_to_zero(x)
# Need to define x again because it's changed now
x <- c(0, -4, 1, -2, 2, 4, -3, -1, 3)
change_negatives_to_zero_with_cloning(x)
*/
Editar y ejecutar código