Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting occurrences without modifying the original order

Tags:

dataframe

r

I am currently searching an easy way to count the occurrences without modifying the order of my dates. I have a column of my dataframe with a lot of dates and I want to count the number of occurrences a date appears.

Let's say I have this list :

data[,1]
18/12/2015
18/12/2015
18/12/2015
01/01/2016
02/02/2016
02/02/2016

I can use the function table() to count the number of occurrences like that : table(data[,1])

But the result will be shown like this :

   Var       freq
01/01/2016    1
02/02/2016    2
18/12/2015    3

And I don't want this order, I would want to keep the original order shown above. I was searching for an option which can cancel the ordering of the function but it seems it doesn't exist. (same for function aggregate())

Has someone an idea ?

like image 548
Mbr Mbr Avatar asked Jun 13 '16 13:06

Mbr Mbr


2 Answers

Here are two options.

First I'll create some data:

> set.seed(123)
> x <- sample(LETTERS[1:5], 10, TRUE)
> x
 [1] "B" "D" "C" "E" "E" "A" "C" "E" "C" "C"

At this point table(x) gives the results in sorted order:

> table(x)
x
A B C D E 
1 1 4 1 3 

What @akrun suggested is creating a factor with specified levels, which gets you the order you want:

> y <- factor(x, levels=unique(x))
> table(y)
y
B D C E A 
1 1 4 3 1 

Or, you can also just re-sort the original table according to ranks like this:

> table(x)[rank(unique(x))]
x
B D C E A 
1 1 4 3 1 

Thanks to @lmo, an even more concise way to do this is simply:

> table(x)[unique(x)]
x
B D C E A 
1 1 4 3 1 
like image 65
mrip Avatar answered Sep 24 '22 01:09

mrip


# Your data
data <- read.table(text="18/12/2015
18/12/2015
18/12/2015
01/01/2016
02/02/2016
02/02/2016")

require(data.table)
dt <- data.table( data )

#  Your data looks like this:
dt
#           V1
#1: 18/12/2015
#2: 18/12/2015
#3: 18/12/2015
#4: 01/01/2016
#5: 02/02/2016

#  The result is this:
dt[ , .N , by = V1 ]
#          V1 N
#1: 18/12/2015 3
#2: 01/01/2016 1
#3: 02/02/2016 2
like image 35
Simon O'Hanlon Avatar answered Sep 22 '22 01:09

Simon O'Hanlon