Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the frequency of an element in a data frame [duplicate]

Tags:

r

I have the following data frame

SelectVar

   b    c    e    f    g    h    j 
1 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2
2 Dxb2 Dxb2 Dxb2 Dxb2 Dxc2 Dxc2 Dxc2
3 Dxd2 Dxi2 tneg tpos Dxd2 Dxi2 tneg

When applying count I get

count(SelectVar)

   b    c    e    f    g    h    j   freq
1 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2   1
2 Dxb2 Dxb2 Dxb2 Dxb2 Dxc2 Dxc2 Dxc2   1
3 Dxd2 Dxi2 tneg tpos Dxd2 Dxi2 tneg   1

When I apply

count(SelectVar==Dxa2)

     b     c     e     f     g     h     j     freq
1 FALSE FALSE FALSE FALSE FALSE FALSE FALSE     1 

I can not figure out how to count the frequency of the different elements Dxa2, Dxb2... in SelectVar

like image 863
Barnaby Avatar asked Feb 04 '14 23:02

Barnaby


2 Answers

You can turn your data.frame to a vector and then use table

df <- read.table(text = "   b    c    e    f    g    h    j 
1 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2
2 Dxb2 Dxb2 Dxb2 Dxb2 Dxc2 Dxc2 Dxc2
3 Dxd2 Dxi2 tneg tpos Dxd2 Dxi2 tneg", header = TRUE, row.names = 1)

table(unlist(df))
## Dxa2 Dxb2 Dxd2 Dxi2 tneg tpos Dxc2 
##    7    4    2    2    2    1    3 

You can turn the result to a data.frame too

as.data.frame(table(unlist(df)))
##   Var1 Freq
## 1 Dxa2    7
## 2 Dxb2    4
## 3 Dxd2    2
## 4 Dxi2    2
## 5 tneg    2
## 6 tpos    1
## 7 Dxc2    3
like image 150
dickoa Avatar answered Sep 30 '22 12:09

dickoa


Use table(), especially good if they're factors (which your data appears to contain):

first <- c("a", "b", "c")
sec <- c("a", "b", "b")
third <- c("b","c","c")
myframe <- cbind(first, sec, third)
table(myframe)

myframe
a b c 
2 4 3

Though if you have numeric columns you might get huge, unreadable output.

like image 28
TomR Avatar answered Sep 30 '22 10:09

TomR