Skip to content

as.matrix.data.table incorrect results when nrows == 1 #2930

@malcook

Description

@malcook

# Minimal reproducible example

library(data.table)
d<-data.table(name=c("bob","joe"),age=10:11,IQ=c(130,140))
as.matrix(d, 1) 
#>     age  IQ
#> bob  10 130
#> joe  11 140

as.matrix(d[1, ], 1)
#>   name  age  IQ   
#> 1 "bob" "10" "130"

Created on 2018-06-13 by the reprex package (v0.2.0).

The problem is that the rownames argument to as.matrix.data.table is not being respected as documented:

rownames: optional, a single column name or column index to use as the
'rownames' in the returned 'matrix'. If 'TRUE' the 'key' of
the 'data.table' will be used if it is a single column,
otherwise the first column in the 'data.table' will be used.
Alternative a vector of length 'nrow(x)' to assign as the row
names of the returned 'matrix'.

We should expect the 2nd call above to yield a 1x2 matrix of numeric having the single rowname of "bob". Instead, it yields a 1x3 character matrix.

R version 3.4.3 (2017-11-30)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

Matrix products: default
BLAS: /n/apps/CentOS7/install/r-3.4.3/lib64/R/lib/libRblas.so
LAPACK: /n/apps/CentOS7/install/r-3.4.3/lib64/R/lib/libRlapack.so

locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] data.table_1.11.2 devtools_1.13.5  

loaded via a namespace (and not attached):
[1] compiler_3.4.3 withr_2.1.2    memoise_1.1.0  digest_0.6.15

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions