Skip to content

Commit

Permalink
tbl_df automatically generates column names. closes #1606
Browse files Browse the repository at this point in the history
  • Loading branch information
romainfrancois committed Feb 8, 2016
1 parent 8691bce commit 34da666
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 9 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# dplyr 0.4.3.9000

* `tbl_df` automatically generates column names (#1606).

* `mutate` failed to deep copy data that ends up in a list column (#1643).

* `mutate` handles adding a factor that is all `NA` (#1645).
Expand Down
38 changes: 29 additions & 9 deletions src/matrixToDataFrame.cpp
Original file line number Diff line number Diff line change
@@ -1,17 +1,41 @@
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List matrixToDataFrame(RObject x) {
SEXPTYPE type = TYPEOF(x);

IntegerVector get_dim( const RObject& x){
if (!x.hasAttribute("dim"))
stop("`x` is not a matrix");

IntegerVector dim = x.attr("dim");
if (dim.size() != 2)
stop("`x` is not a matrix");

return dim ;
}

CharacterVector get_names( const RObject& x, const IntegerVector& dim){
int nc = dim[1] ;
if( x.hasAttribute("dimnames") ){
List dimnames = x.attr("dimnames") ;
try {
CharacterVector res( dimnames[1] ) ;
return res ;
} catch(...){}
}

CharacterVector names( nc ) ;
for( int i=0; i<nc; i++){
names[i] = tfm::format( "V%d", (i+1) ) ;
}
return names ;
}

// [[Rcpp::export]]
List matrixToDataFrame(RObject x) {
SEXPTYPE type = TYPEOF(x);

IntegerVector dim = get_dim(x) ;
CharacterVector names = get_names(x, dim) ;

int nrow = dim[0], ncol = dim[1];

List out = List(ncol);
Expand Down Expand Up @@ -42,11 +66,7 @@ List matrixToDataFrame(RObject x) {
}
}

if (x.hasAttribute("dimnames")) {
List dimnames = x.attr("dimnames");
out.attr("names") = dimnames[1];
}

out.attr("names") = names ;
out.attr("class") = CharacterVector::create("tbl_df", "tbl", "data.frame");
out.attr("row.names") = IntegerVector::create(NA_INTEGER, -nrow);

Expand Down
14 changes: 14 additions & 0 deletions tests/testthat/test-data_frame.R
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,17 @@ test_that("names must be unique (#820)", {
"Each variable must have a unique name"
)
})

test_that("data frame column names are automatically generated (#1606)", {
m <- matrix( 1:6, nr = 3)
df <- tbl_df(m)
expect_equals( names(df), c("V1", "V2") )

row.names(m) <- 1:3
df <- tbl_df(m)
expect_equals( names(df), c("V1", "V2") )

colnames(m) <- c("a", "b")
df <- tbl_df(m)
expect_equals( names(df), c("a", "b") )
})

0 comments on commit 34da666

Please sign in to comment.