Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Frequency count of two column in R

Tags:

r

I have two columns in data frame

2010  1 2010  1 2010  2 2010  2 2010  3 2011  1 2011  2 

I want to count frequency of both columns and get the result in this format

  y    m Freq  2010  1 2  2010  2 2  2010  3 1  2011  1 1  2011  2 1  
like image 959
Sunny Sunny Avatar asked Jun 04 '12 10:06

Sunny Sunny


People also ask

How do I count the frequency of an element in a column in R?

The sapply() method, which is used to compute the frequency of the occurrences of a variable within each column of the data frame. The sapply() method is used to apply functions over vectors or lists, and return outputs based on these computations.

How can I get the frequency counts of each item in one or more columns in a Dataframe?

size() Using df. groupby(). size() function to get count frequency of single or multiple columns, when you are trying with multiple columns use size() method.


2 Answers

I haven't seen a dplyr answer yet. The code is rather simple.

library(dplyr) rename(count(df, y, m), Freq = n) # Source: local data frame [5 x 3] # Groups: V1 [?] # #       y     m  Freq #   (int) (int) (int) # 1  2010     1     2 # 2  2010     2     2 # 3  2010     3     1 # 4  2011     1     1 # 5  2011     2     1 

Data:

df <- structure(list(y = c(2010L, 2010L, 2010L, 2010L, 2010L, 2011L,  2011L), m = c(1L, 1L, 2L, 2L, 3L, 1L, 2L)), .Names = c("y", "m" ), class = "data.frame", row.names = c(NA, -7L)) 
like image 25
Rich Scriven Avatar answered Oct 07 '22 17:10

Rich Scriven


If your data is dataframe df with columns y and m

library(plyr) counts <- ddply(df, .(df$y, df$m), nrow) names(counts) <- c("y", "m", "Freq") 
like image 129
danas.zuokas Avatar answered Oct 07 '22 16:10

danas.zuokas