'Create a new column from a conditional contents of two other columns in same row
Suppose I have dataset mtcars.
Suppose I want to create a new column called mtcars$newcol based on the lower value in each row of mtcars$gear and mtcars$cars.
head(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
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
What I want is :
mpg cyl disp hp drat wt qsec vs am gear carb newcol
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4 3
Note that the value in newcol is the lower of the gear and carb row.
Solution 1:[1]
mtcars %>%
rowwise() %>%
mutate(newcol = min(gear, carb))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | stomper |
