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 – rename()
Renaming a variable with rename():
Renaming a variable in a data frame in R is surprisingly hard to do! The rename() function is designed to make this process easier.
For the examples in this section we will be using a built-in data set in R called trees data set. First load the data set using data(“trees”) command. To the help file for trees just type ?trees. Don’t forget to load the dplyr package.
library(dplyr)
library(datasets)
#OR
data("trees")?trees
You can see some basic characteristics of the dataset with the dim() and str() functions.
dim(trees)
str(trees)
names(trees)
Output:
> dim(trees)
[1] 31 3
> str(trees)
'data.frame': 31 obs. of 3 variables:
$ Girth : num 8.3 8.6 8.8 10.5 10.7 10.8 11 11 11.1 11.2 ...
$ Height: num 70 65 63 72 81 83 66 75 80 75 ...
$ Volume: num 10.3 10.3 10.2 16.4 18.8 19.7 15.6 18.2 22.6 19.9 ...
> names(trees)
[1] "Girth" "Height" "Volume"
Example:
mydata <- rename(trees, "Tree Diameter in Inches"=Girth, "Height in ft"=Height, "Volume of Timber"=Volume)
head(mydata)
Output:
Tree Diameter in Inches Height in ft Volume of Timber
1 8.3 70 10.3
2 8.6 65 10.3
3 8.8 63 10.2
4 10.5 72 16.4
5 10.7 81 18.8
6 10.8 83 19.7