Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

How to save all columns after mutate_each?

$
0
0

I have the task: to convert some given columns into factors, all other columns should stay as is. Criteria for converting into factor: if the meaning is less than the column mean, than it is 0. Otherwise 1. I used mutate_each function

library(dplyr)
test_data <- mtcars[1:4]
factors = c(1, 3)
new <- mutate_each(test_data[factors], funs(as.factor(ifelse(. < mean(.), 0,1))))

but it stays only factors columns:

mpg disp
1    1    0
2    1    0
3    1    0
4    1    1
5    0    1
6    0    0
7    0    1
8    1    0
9    1    0
10   0    0
11   0    0
12   0    1
13   0    1
14   0    1
15   0    1
16   0    1
17   0    1
18   1    0
19   1    0
20   1    0
21   1    0
22   0    1
23   0    1
24   0    1
25   0    1
26   1    0
27   1    0
28   1    0
29   0    1
30   0    0
31   0    1
32   1    0

I need to get the df with all columns in the original orders. cbind does not work because it changes the order of columns. I want to get this result:

        mpg cyl disp  hp
Mazda RX4             1   6    0 110
Mazda RX4 Wag         1   6    0 110
Datsun 710            1   4    0  93
Hornet 4 Drive        1   6    1 110
Hornet Sportabout     0   8    1 175
Valiant               0   6    0 105
Duster 360            0   8    1 245
Merc 240D             1   4    0  62
Merc 230              1   4    0  95
Merc 280              0   6    0 123
Merc 280C             0   6    0 123
Merc 450SE            0   8    1 180
Merc 450SL            0   8    1 180
Merc 450SLC           0   8    1 180
Cadillac Fleetwood    0   8    1 205
Lincoln Continental   0   8    1 215
Chrysler Imperial     0   8    1 230
Fiat 128              1   4    0  66
Honda Civic           1   4    0  52
Toyota Corolla        1   4    0  65
Toyota Corona         1   4    0  97
Dodge Challenger      0   8    1 150
AMC Javelin           0   8    1 150
Camaro Z28            0   8    1 245
Pontiac Firebird      0   8    1 175
Fiat X1-9             1   4    0  66
Porsche 914-2         1   4    0  91
Lotus Europa          1   4    0 113
Ford Pantera L        0   8    1 264
Ferrari Dino          0   6    0 175
Maserati Bora         0   8    1 335
Volvo 142E            1   4    0 109

Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>