CrishaD
CrishaD

Reputation: 51

Order a dataframe by column values with R

I have a dataframe given by

x <- c(1,3,4,5,6,9,7,8,9,2,1)
y <- c("A", "A", "B", "C", "C", "C","A", "B", "C", "C", "C")

df <- data.frame(x,y)

I want to order it with respect column y.

I did something like

orderdf <- df[order(df$y),]

and I got on the y columns

AAABBCCCCCC

but actually I want to order it also by numerosity so on my y column I want to obtain

BBAAACCCCCC

How can I do it?

Moreover I would also like to count how many (I have no clue about this) to obtain:

B 2


A 3


C 6 

Thank you!

Upvotes: 2

Views: 119

Answers (2)

akrun
akrun

Reputation: 887711

Using dplyr

library(dplyr)
df %>%
  group_by(y) %>%
  mutate(count = n()) %>%
  arrange(count, y) %>%
  select(-count)

Upvotes: 0

lmo
lmo

Reputation: 38520

This should do the trick:

# construct count variable
df$count <- ave(df$x, df$y, FUN=length)
# order it up
df[order(df$count, df$y),]

Another nice way to obtain counts is using table:

table(df$y)    

Upvotes: 3

Related Questions