Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert data.frame to data.table column missing

Had a case like this. Tried to convert "mtcars" class from data.frame to data.table.

"mtcars" data:

> mtcars
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1

Original class is "data.frame".

> str(mtcars)
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

Convert to data.table. Found the Column for car brands are gone. Why? How to retain the column of brands?

> mtcars2 <- data.table(mtcars)
> mtcars2
     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
 1: 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
 2: 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
 3: 22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1

Would like to have a data.table with final data format as below -- having a NEW column name "Brands" for the first column of brands. How to code to add the column "Brands" from the original "mtcars" dataset?

Brands              mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
like image 707
KFB Avatar asked May 19 '13 13:05

KFB


1 Answers

It's the rownames that are missing, not one of the columns.

If you want Brands as a column, the manual approach is:

data.table(Brands = rownames(mtcars), mtcars)

Alternately:

data.table(mtcars, keep.rownames = TRUE)

However, this does not make the resulting data.table have the old rownames, it just makes a column for them, called "rn". This is in the documentation, ?data.table.


Alternately, modify the table in place, for DF = mtcars:

setDT(DF, keep.rownames = "Brands")

Minor point: we cannot setDT(mtcars, ...), since mtcars is a built-in table.

like image 109
Frank Avatar answered Oct 17 '22 06:10

Frank