r - convert data.frame to data.table column missing -
had case this. tried convert "mtcars" class data.frame data.table.
"mtcars" data:
> mtcars mpg cyl disp hp drat wt qsec vs 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 "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 ... $ : 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 data.table. found column car brands gone. why? how retain column of brands?
> mtcars2 <- data.table(mtcars) > mtcars2 mpg cyl disp hp drat wt qsec vs 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 have data.table final data format below -- having new column name "brands" first column of brands. how code add column "brands" original "mtcars" dataset?
brands mpg cyl disp hp drat wt qsec vs 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
it's rownames missing, not 1 of columns.
if want brands column, manual approach is:
data.table(brands = rownames(mtcars), mtcars)
alternately:
data.table(mtcars, keep.rownames = true)
however, not make resulting data.table have old rownames, makes column them, called "rn". in documentation, ?data.table
.
alternately, modify table in place, df = mtcars
:
setdt(df, keep.rownames = "brands")
minor point: cannot setdt(mtcars, ...)
, since mtcars
built-in table.
Comments
Post a Comment