I am new to R and currently trying to wrap my head around dataframes in R. I want to sort a dataframe by the column values, and then return the top of it after it has been sorted.
As of now I only seem to get one row back. I used the "iris" dataframe.
sort <- function(df, var.name, n){
df1 <- df[rev(order(var.name)), ]
sorted <- head(df1, n)
return(sorted)
}
sort_head(df = iris, var.name = "Petal.Length", n = 10)
# My output
> sort_head(df = iris, var.name = "Petal.Length", n = 5)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
My ordering of the dataframe seems to rewrite the dataframe to only contain one row - whereas all the guides (e.g here) I've found simply rewrites the dataframe to be sorted by column. What am I missing?