Course
Data Frames
Convert a List to a DataframeCreate an Empty DataframeCombine Two Dataframe into OneChange Column Name of a DataframeExtract Columns From a DataframeDrop Columns in a DataframeReorder Columns in a DataframeSplit DataframeMerge Multiple DataframesDelete Rows From DataframeMake a List of DataframesIntroduction
"Hello World" ProgramAdd Two VectorsFind Sum, Mean and Product of Vector in R ProgrammingTake Input From UserGenerate Random Number from Standard DistributionsSample from a PopulationFind Minimum and MaximumSort a VectorStrings
Concatenate Two StringsFind the Length of a StringCheck if Characters are Present in a StringExtract n Characters From a StringReplace Characters in a StringCompare two StringsConvert Factors to CharactersTrim Leading and Trailing WhitespacesVectors
Concatenate a Vector of StringsCheck if a Vector Contains the Given ElementCount the Number of Elements in a VectorFind Index of an Element in a VectorAccess Values in a VectorAdd Leading Zeros to VectorR Program to Reorder Columns in a Dataframe
Example 1: Reorder R Dataframe Columns Using Column Name
# import dplyr package
library(dplyr)
# Create a data frame
dataframe1 <- data.frame (
Age = c(22, 15, 19),
Address = c("Nepal", "USA", "Germany"),
Name = c("Juan", "Alcaraz", "Simantha")
)
# rearrange columns in Name, Age, Address order
print(select(dataframe1, Name, Age, Address))
Output
Name Age Address
1 Juan 22 Nepal
2 Alcaraz 15 USA
3 Simantha 19 Germany
In the above example, we have used the select()
function provided by the dplyr
package to reorder columns of the dataframe named dataframe1.
select(dataframe1, Name, Age, Address)
Here, inside select()
,
dataframe1
- a dataframe whose column is to be reorderedName, Age, Address
- new order of columns
Hence the order of dataframe1 column is changed from Age, Address, Name
to Name Age Address
.
Example 2: Reorder R Dataframe Columns by Column Position
# import dplyr package
library(dplyr)
# Create a data frame
dataframe1 <- data.frame (
Age = c(22, 15, 19),
Address = c("Nepal", "USA", "Germany"),
Name = c("Juan", "Alcaraz", "Simantha")
)
# rearrange columns in Name, Age, Address order
print(select(dataframe1, 3, 1, 2))
Output
Name Age Address
1 Juan 22 Nepal
2 Alcaraz 15 USA
3 Simantha 19 Germany
In the above example, we have used the column position inside select()
to reorder columns of dataframe1.
select(dataframe1, 3, 1, 2)
Here, the 3rd column is now 1st column, 1st column is now 2nd column and 2nd column is now 3rd column.