Categories
data science

Reordering Columns and Rows – R

How to reorder columns and rows in a dataframe.

We start with three vectors which we will put into a data frame called tDF

column1<-c(0.03488372,0.02543007,0.03018868)
column2<-c(0.11627907,0.10994764,0.13584906)
column3<-c(0.8488372,0.8646223,0.8339623)

tDF<-data.frame(column1,column2,column3)

Renaming Columns

There is away of entering the names when building the data frame, like this…

tDF<-data.frame('core'=column1,'middle'=column2,'periphery'=column3)

But let’s just prentend we forgot to do that, and instead we’ve ended up with a dataframe like this.

     column1   column2   column3
1 0.03488372 0.1162791 0.8488372
2 0.02543007 0.1099476 0.8646223
3 0.03018868 0.1358491 0.8339623

We can list the column names like this…

names(tDF)

# which returns
[1] "column1" "column2" "column3"

We can change the names to “core”, “middle”, “periphery” like this

names(tDF)<-c('Core','Middle','Periphery')

now checking the names will return the new names…

names(tDF)
[1] "Core"      "Middle"    "Periphery"

If we check the data frame, it will look something like this

        Core    Middle Periphery
1 0.03488372 0.1162791 0.8488372
2 0.02543007 0.1099476 0.8646223
3 0.03018868 0.1358491 0.8339623

Swap columns and rows

But what we want is to swap the rows for the columns, which is as easy as this

tDF2<-data.frame(t(tDF))

now the new dataframe will look something like this

                  X1         X2         X3
Core      0.03488372 0.02543007 0.03018868
Middle    0.11627907 0.10994764 0.13584906
Periphery 0.84883720 0.86462230 0.83396230

Ordering the Rows

Finally, we want to order the rows with the higher values at the top and the lower values at the bottom. This we can do by ordering the rows in descending order using the values of the first column. Like this

tdf3<-tDF2[order(-tDF2[1]),]

so the new dataframe should look a bit like this

                  X1         X2         X3
Periphery 0.84883720 0.86462230 0.83396230
Middle    0.11627907 0.10994764 0.13584906
Core      0.03488372 0.02543007 0.03018868

DONE!!

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s