It is not because you have imported your data from an external source that the order of the observations has to stay as it originally was. You can sort the observations based on ascending or descending values in a column. To do so, you will use the function object.name[order(object.name[,X]),a:b]
where X
is the number of the column by which the data shall be sorted (this can be replaced by the name of the variable placed between quotation marks), a:b
is the range of columns to display. Here we sort our whole dataframe based on the content of Var1
in column 2 using the command my.imported.data[order(my.imported.data[,2]),1:4]
[code language=”r”]
my.imported.data[order(my.imported.data["Var1"]),1:4]
[/code]
If you are interested in getting it sorted in the reverse order (descending values in Var1
), use the function rev()
in the following manner:
[code language=”r”]
my.imported.data[rev(order(my.imported.data["Var1"])),1:4]
[/code]
Note that the last part of the function defines what you want to display. Here we chose to display the range of columns 1:4
but we could have restricted the display to anything else using the function concatenate
. Let’s display the sorted dataframe only with Var1
and Var3
:
[code language=”r”]
my.imported.data[rev(order(my.imported.data["Var1"])),c("Var1", "Var3")]
[/code]