library(MASS)
data(petrol)
data(Cars93)
head(petrol)
Rename
names(petrol) <- c("ID", "SpecGrav", "VaporPressure", "VolCrude", "VolGas", "PercCrude" )
head(petrol)
The order() gives a vector of numbers relating to a row
order(petrol$VaporPressure)
## [1] 30 31 32 25 26 27 21 22 23 24 28 29 5 6 7 15 16 17 18 19 20 8 9
## [24] 10 11 12 13 14 1 2 3 4
Use in subsetting to rearrange a data frame from lowest to highest
petrol[order(petrol$VaporPressure),]
Decreasing order
petrol[order(petrol$VaporPressure,decreasing=TRUE),]
Order by multiple variables – first by vapor pressure then volatility of gas
petrol[order(petrol$VaporPressure, petrol$VolGas, decreasing = T),]
Create a new dataset ordered by
newpetrol <- petrol[order(petrol$PercCrude, decreasing = T),]
newpetrol
Reorder columns (ex. alphabetical order)
newpetrol <- newpetrol[,order(names(petrol))]
newpetrol
Cars93[, c("Model", "Type", "Price")]
A logical function that returns matching values that makes the statement True
Cars93[,which(colnames(Cars93)=="Model")]
## [1] Integra Legend 90 100
## [5] 535i Century LeSabre Roadmaster
## [9] Riviera DeVille Seville Cavalier
## [13] Corsica Camaro Lumina Lumina_APV
## [17] Astro Caprice Corvette Concorde
## [21] LeBaron Imperial Colt Shadow
## [25] Spirit Caravan Dynasty Stealth
## [29] Summit Vision Festiva Escort
## [33] Tempo Mustang Probe Aerostar
## [37] Taurus Crown_Victoria Metro Storm
## [41] Prelude Civic Accord Excel
## [45] Elantra Scoupe Sonata Q45
## [49] ES300 SC300 Continental Town_Car
## [53] 323 Protege 626 MPV
## [57] RX-7 190E 300E Capri
## [61] Cougar Mirage Diamante Sentra
## [65] Altima Quest Maxima Achieva
## [69] Cutlass_Ciera Silhouette Eighty-Eight Laser
## [73] LeMans Sunbird Firebird Grand_Prix
## [77] Bonneville 900 SL Justy
## [81] Loyale Legacy Swift Tercel
## [85] Celica Camry Previa Fox
## [89] Eurovan Passat Corrado 240
## [93] 850
## 93 Levels: 100 190E 240 300E 323 535i 626 850 90 900 Accord ... Vision
Subset by rows and columns simultaneously
Cars93[which(Cars93$Cylinders==8), c("Model", "Price")]
Get the mean price of 8 cylinder cars
mean(Cars93[which(Cars93$Cylinders==8), "Price"])
## [1] 33.78571
Create new data
Forddata <- Cars93[-which(Cars93$Manufacturer=="Ford"), c("Model", "Price", "MPG.city", "Cylinders")]
Forddata
Exclude data
Forddata[-which(Forddata$Cylinders == 6),]