Reputation: 1480
I have the following data frame (this is an example and the dataframe can contain more columns)
SelectVar
a b c l p v aa ff
1 Dxa2 Dxa2 Dxa2 Dxa2 Dxa2 Dxb2 Dxb2 Dxb2
2 Dxb2 Dxb2 Dxb2 Dxd2 Dxi2 Dxc2 Dxd2 Dxi2
3 Dxc2 Dxd2 Dxi2 Dxi2 tneg Dxd2 Dxi2 tneg
I would like to count the frequency of the elements without convert it into a vector and using table or by indicating the element like in
length(SelectVar[SelectVar=="Dxa2"])
Is there any other way as to count the frequencies of the elements than the two mentioned in the above paragraph for the sample dataframe.
Upvotes: 0
Views: 1451
Reputation: 3711
I think you asked the same question yesterday, Counting the frequency of an element in a data frame
answer modified from, dickoa's answer to previous question
instead of data.frame
, if you make it matrix, table()
does not need vectorization and it should work.
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)
ll<-data.frame(table(as.matrix(df)))
now, you can sort by freq
and select top 3
head(ll[order(ll$Freq, decreasing=T),],3)
Upvotes: 2