Home > Software engineering >  Sorting a dataframe in R [duplicate]
Sorting a dataframe in R [duplicate]

Time:09-24

I am trying to sort a dataframe in ascending order which I'm confused at.

Example:

Label | Data
B3        2
B1        3
B2        4

What I'm trying to achieve is:

Label | Data
B1        3
B2        4
B3        2

I am using R without any Library.

CodePudding user response:

In base R, you can use order:

Label <- c("B3","B1","B2")
Data <- c(2,3,4)
df <- data.frame(Label,Data)
> df
  Label Data
1    B3    2
2    B1    3
3    B2    4
df = df[order(Label),]
> df
  Label Data
2    B1    3
3    B2    4
1    B3    2

CodePudding user response:

In case you want to use tidyverse later, with dplyr you can use arrange:

Label <- c("B3","B1","B2")
Data <- c(2,3,4)
df <- data.frame(Label,Data)

library(dplyr)

df %>% 
  arrange(Label)

  Label Data
1    B1    3
2    B2    4
3    B3    2
  • Related