1

Using the dataframe mtcars, how do I make a new dataframe that uses all columns from dataframe except gear? IN the new dataframe, I'd like to separate each unique gear value into a column. How do I do that?

stevec
  • 41,291
  • 27
  • 223
  • 311
Username
  • 3,463
  • 11
  • 68
  • 111

3 Answers3

2

This will do all that you're after


library(fastDummies)

# Numerically encode gear column as dummy variables
mt_cars_with_gear_dummy_variables <- fastDummies::dummy_cols(mtcars, select_columns = "gear")


# Remove original gear column
mt_cars_with_gear_dummy_variables[, !names(mt_cars_with_gear_dummy_variables) %in% c("gear")] 


mt_cars_with_gear_dummy_variables

stevec
  • 41,291
  • 27
  • 223
  • 311
  • suggestion: better to do `fastDummies::dummy_cols(mtcars, select_columns = "gear")` and then drop the `gear` column. – Mankind_008 Feb 09 '19 at 05:04
  • @Mankind_008 much nicer, as it names the dummy columns nicely (unlike when providing a vector as before). I have updated the answer to reflect – stevec Feb 09 '19 at 05:06
1

You can do this in one step with model.matrix:

model.matrix(~ . + gear - 1, mtcars)

Which gives:

                     mpg cyl  disp  hp drat    wt  qsec vs am gear3 gear4 gear5 carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1     0     1     0    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1     0     1     0    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1     0     1     0    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0     1     0     0    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0     1     0     0    2
...
Maserati Bora       15.0   8 301.0 335 3.54 3.570 14.60  0  1     0     0     1    8
Volvo 142E          21.4   4 121.0 109 4.11 2.780 18.60  1  1     0     1     0    2
Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56
0

Use select: select(model.matrix, - gear)