Modifying a Data Frame

Dirk Eddelbuettel — written Dec 14, 2012 — source

Data frames can be manipulated using the DataFrame class. The indvidiual vectors composing a data frame can be accessed by name, modified, and then recombined into a new data frame.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
DataFrame modifyDataFrame(DataFrame df) {

  // access the columns
  IntegerVector a = df["a"];
  CharacterVector b = df["b"];
  // make some changes
  a[2] = 42;
  b[1] = "foo";       

  // return a new data frame
  return DataFrame::create(_["a"]= a, _["b"]= b);

Note the use of the _["a"] syntax to create named arguments to the DataFrame::create function.

The function returns a modified copy of the data frame:

df <- data.frame(a = c(1, 2, 3),
                 b = c("x", "y", "z"))

   a   b
1  1   x
2  2 foo
3 42   z

tags: dataframe 

Related Articles