R Programming
- Overview of R
- Installing R on Windows
- Download and Install RStudio on Windows
- Setting Your Working Directory (Windows)
- Getting Help with R
- Installing R Packages
- Loading R Packages
- Take Input and Print in R
- R Objects and Attributes
- R Data Structures
- R – Operators
- Vectorization
- Dates and Times
- Data Summary
- Reading and Writing Data to and from R
- Control Structure
- Loop Functions
- Functions
- Data Frames and dplyr Package
- Generating Random Numbers
- Random Number Seed in R
- Random Sampling
- Data Visualization Using R
dplyr Package – arrange()
Arrange rows with arrange():
The arrange() function is used to reorder rows of a data frame according to one of the variables. Reordering rows of a data frame (while preserving corresponding order of other columns) is normally a pain to do in R. The arrange() function simplifies the process quite a bit.
For the examples in this section we will be using a built-in data set in R called mtcars data set. First load the data set using data(“mtcars”) command. To the help file for mtcars just type ?mtcars. Don’t forget to load the dplyr package.
library(dplyr)
library(datasets)
#OR
data("mtcars")?mtcars
You can see some basic characteristics of the dataset with the dim() and str() functions.
dim(mtcars)
str(mtcars)
names(mtcars)
Output:
dim(mtcars)
[1] 32 11
> 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 …
$ am : 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 …
> names(mtcars)
[1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" "carb"
Example:
x<-arrange(mtcars, cyl)
head(select(x, mpg , cyl), 10)
tail(select(x, mpg , cyl), 10)
Output:
head(select(x, mpg , cyl), 10)
mpg cyl
1 22.8 4
2 24.4 4
3 22.8 4
4 32.4 4
5 30.4 4
6 33.9 4
7 21.5 4
8 27.3 4
9 26.0 4
10 30.4 4
> tail(select(x, mpg , cyl), 10)
mpg cyl
23 15.2 8
24 10.4 8
25 10.4 8
26 14.7 8
27 15.5 8
28 15.2 8
29 13.3 8
30 19.2 8
31 15.8 8
32 15.0 8
Example 2:
Columns can be arranged in descending order too by useing the special desc() operator.
y<-arrange(mtcars, desc(cyl))
head(select(y, mpg , cyl), 10)
tail(select(y, mpg , cyl), 10)
Output:
> head(select(y, mpg , cyl), 10)
mpg cyl
1 18.7 8
2 14.3 8
3 16.4 8
4 17.3 8
5 15.2 8
6 10.4 8
7 10.4 8
8 14.7 8
9 15.5 8
10 15.2 8
> tail(select(y, mpg , cyl), 10)
mpg cyl
23 24.4 4
24 22.8 4
25 32.4 4
26 30.4 4
27 33.9 4
28 21.5 4
29 27.3 4
30 26.0 4
31 30.4 4
32 21.4 4